How to use Python's range function
1. What is the range() function?
The range() function is a built-in function of python. It can return a series of consecutively added integers and can generate a list object.
Most of them often appear in for loops and can be used as indexes in for loops.
Quick question practice: for..range practice
1: Use for loop and range to find all even numbers within 0 ~ 100, and append them to a list.
1 2 3 4 |
|
2: Use for loop and range to find the number within 0 ~ 50 that can be divided by 3, and append it to a list.
1 2 3 4 5 |
|
3: Use for loop and range to find the number that is divisible by 3 within 0 ~ 50, and insert it into the 0th index position of the list. The final result is as follows: [48,45,42.. .]
1 2 3 4 5 |
|
4: Find the elements in the list li, remove the spaces before and after each element, and find the elements starting with "a", add them to a new list, and finally print the new list in a loop list.
1 2 3 4 5 6 7 8 9 |
|
2. Grammar format
1 |
|
Parameter introduction:
start refers to the starting value of counting and can be omitted If not written, the default is 0;
stop refers to the end value of the count, but does not include stop;
step is the step size, the default is 1 and cannot be 0.
(Special note: if there are three parameters, then the last parameter is expressed as the step size.)
ps1: Only one parameter : Indicates all integers from 0 to this parameter, excluding the parameter itself
1 2 3 4 5 6 7 8 9 |
|
ps2:
When the range function has 2 parameters, the first parameter represents Left boundary, the second parameter represents the right boundary, including left but not right.
1 2 3 4 5 6 |
|
ps3: When
range contains 3 parameters, the first one represents the left boundary, the second represents the right border, and the third represents the step size. , that is, the difference between two integers, including the left but not the right.
1 2 3 4 5 6 7 |
|
The running result is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 , 13, 14, 15]
range(1, 16)
range(1, 16, 2)
[1, 3, 5, 7, 9, 11, 13, 15]
Example:
1 2 3 4 5 6 7 8 |
|
Run result:
Example 1: The starting value is 1, the ending value is 10123456789 Example 2: The end value is 100123456789 Example 3: The end value is 10, the step size is 213579
3. Error reporting issue
(1) Error reporting: TypeError: ‘list&rsquo ; object is not callable.
refers to the error type: The "list" object cannot be called
Reason:
Since the variable list and the function list have the same name, when the function uses the list function, it finds that list is a defined list, and the list cannot be called, so a type error is thrown. Therefore, when we define variables in the future, we should avoid duplication of function names, method names and keywords, as in any language.
(2) What if the range function reports an error:
TypeError: ‘float‘ object cannot be interpreted as an integer?
The reason is that range can only generate integers, not float types. Use numpy's arange function to solve the problem:
1 2 3 4 |
|
4. Things to note about the range() function
① It represents an interval that is closed on the left and open on the right;
② The parameter it receives must be an integer, which can be a negative number, but cannot be a floating point number or other types;
1 2 3 4 |
|
③ It is immutable The sequence type can perform operations such as judging elements, finding elements, slicing, etc., but cannot modify elements;
④ It is an iterable object, but not an iterator.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
5. Range objects are immutable sequences
The official division is clear like this - there are three basic sequence types: list, tuple and range (range) object.
(There are three basic sequence types: lists, tuples, and range objects.)
The range type is a basic sequence in the same position as lists and tuples! What is the difference between range sequence and other sequence types?
Normal sequences support 12 operations, and range sequences only support 10 of them. Additive splicing and multiplication repetition are not supported.
1 2 3 |
|
Then the question arises: is also an immutable sequence. Why do strings and tuples support the above two operations, but range sequences do not?
Although immutable sequences cannot be modified directly, we can copy them to new sequences for operation. Why doesn’t the range object even support this?
Explanation from the official document:
...due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violates that pattern.
The reason is that the range object only represents a sequence that follows a strict pattern, and repetition and splicing usually violate this pattern...
问题的关键就在于 range 序列的 pattern!仔细想想,其实它表示的就是一个等差数列,拼接两个等差数列,或者重复拼接一个等差数列,这就是为啥 range 类型不支持这两个操作的原因了。因此可以得出结论,任何修改行为都会破坏等差数列的结构,因此最好不要进行任何修改。
【range类型的优点】
不管range对象表示的整数序列有多长,所有range对象占用的内存空间都是相同的,因为仅仅需要存储start、stop和step。只有当用到range对象时,才会去计算序列中的相关元素。
6、range函数实现逆序遍历
range函数实现逆序遍历两种实现方式
1)先创建一个列表,然后对列表中的元素进行逆序
例如:a=range(4)
1 2 |
|
2)直接使用range()函数完成逆序遍历
1 2 |
|
7、与列表list的使用
1 2 3 |
|
运行结果:
【range与list的区别】
range()是依次取顺序的数值,常与for循环一起用,如for范围内的每个(0, 5):for循环执行5次,每个取值是0〜4。而list()是把字符串转换为列表,如a = ’01234’ , b = list(a), a打印出来会是一个列表:[‘0’,‘1’,‘2’,‘3’,‘4’],如a = [0, 1, 2, 3, 4],输出的结果就会是[0, 1, 2, 3, 4]
1 2 3 4 5 |
|
8、关于range函数小结
(1)range对象的使用和理解都不难,但是在python的使用中非常常用!
(2)range对象既不是函数也不是迭代器,可以叫它“懒序列”;
(3)参数解释:start为范围开始,stop为范围结束,step为步长;
(4)range对象经常和for循环配合使用;
(5)可以对range对象进行索引;
关于range()函数还有一点需要注意的地方:range() 方法生成的只是可迭代对象,并不是迭代器!(Python2 中 range() 生成的是列表,本文基于Python3,生成的是可迭代对象)可以获得迭代器的内置方法很多,例如 zip() 、enumerate()、map()、filter() 和 reversed() 等等,但是像 range() 这样仅仅得到的是可迭代对象的方法就少有了。
在 for-循环 遍历时,可迭代对象与迭代器的性能是一样的,即它们都是惰性求值的,在空间复杂度与时间复杂度上并无差异。两者的差别概括是:相同的是都可惰性迭代,不同的是可迭代对象不支持自遍历(即next()方法),而迭代器本身不支持切片(即__getitem__() 方法)。虽然有这些差别,但很难得出结论说它们哪个更优。
那为什么给 5 种内置方法都设计了迭代器,偏偏给 range() 方法设计的就是可迭代对象呢?把它们都统一起来,不是更好么?事实上,Pyhton 为了规范性就干过不少这种事,例如,Python2 中有 range() 和 xrange() 两种方法,而 Python3 就干掉了其中一种。为什么不更规范点,令 range() 生成的是迭代器呢?
这个问题看到有大佬说的比较好的观点,这里引用一下:
zip() 等方法都需要接收确定的可迭代对象的参数,是对它们的一种再加工的过程,因此也希望马上产出确定的结果来,所以 Python 开发者就设计了这个结果是迭代器。
这样还有一个好处,即当作为参数的可迭代对象发生变化的时候,作为结果的迭代器因为是消耗型的,不会被错误地使用。
而 range() 方法就不同了,它接收的参数不是可迭代对象,本身是一种初次加工的过程,所以设计它为可迭代对象,既可以直接使用,也可以用于其它再加工用途。
例如,zip() 等方法就完全可以接收 range 类型的参数。
1 2 |
|
也就是说,range() 方法作为一种初级生产者,它生产的原料本身就有很大用途,早早把它变为迭代器的话,无疑是一种画蛇添足的行为。重点不在于range对象是什么,而在于我们如何使用它
The above is the detailed content of How to use Python's range function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
