In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "what are the basic uses of the range function in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the basic uses of the range function in Python.
1. What is range ()?
Its syntax: range (start, stop [, step]); start refers to the count start value, the default is 0 position stop refers to the count end value, but does not include stop; step is the step size, the default is 1, cannot be 0. The range () method generates a range of integers that are left closed and right open.
> a = range (5) # that is, range (0Magne5) > arange (0re5) > len (a) 5 > for x in a: > print (xmemend = ") 0 1 2 3 4
For the range () function, there are several points to note: (1) it represents the left closed and right open interval; (2) the parameters it receives must be integers, which can be negative, but not floating-point numbers, etc.; (3) it is an immutable sequence type, which can judge elements, find elements, slice, etc., but cannot modify elements; (4) it is an iterable object, but not an iterator.
# (1) left closed and right open > > for i in range (3,6): > > print (iRegent end= ") 345 # (2) Parameter types > for i in range (- 8,-2,2): > print (I) End= "")-8-6-4 > range (2.2)-- TypeError Traceback (most recent call last)... TypeError: 'float' object cannot be interpreted as an integer # (3) sequence Operation > b = range (1) > b [0] 1 > > b [:-3] range (1) > > b [0] = 2TypeError Traceback (most recent call last)... TypeError: 'range' object does not support item assignment # (4) is not an iterator > hasattr (range (3),' _ iter__') True > hasattr (range (3),'_ next__') False > hasattr (iter (range (3)),'_ next__') True2, why doesn't range () produce iterators?
There are many built-in ways to get iterators, such as zip (), enumerate (), map (), filter (), reversed (), and so on, but range () is the only way to get iterable objects (if there is a counterexample, please let me know). This is where I have the misunderstanding of knowledge.
During for- loop traversal, the performance of iterable objects is the same as that of iterators, that is, they are both lazily evaluated, and there is no difference in space complexity and time complexity. I have summarized that the difference between the two is "two different together": the same is that both are lazy iterations, the difference is that iterable objects do not support self-traversal (that is, the next () method), and the iterator itself does not support slicing (that is, the _ _ getitem__ () method).
Although there are these differences, it is difficult to conclude which of them is better. The subtlety now is why iterators are designed for all five built-in methods, but iterators are designed for the range () method. Wouldn't it be better to unify them all?
In fact, Pyhton has done a lot of this for the sake of standardization. For example, there are two methods in Python2, range () and xrange (), and Python3 kills one of them and uses the "Li Daitao stiff" method. Why not change the specification point so that range () generates an iterator?
On this issue, I have not found an official explanation, the following is purely personal opinion.
Methods such as zip () need to receive certain parameters of iterable objects, which is a process of reprocessing them, so they also want to produce definite results immediately, so Python developers designed this result as an iterator. This also has the advantage that when the iterable object as a parameter changes, the resulting iterator will not be used incorrectly because it is consumable.
The range () method is different, the parameter it receives is not an iterable object, it is a process of initial processing, so it is designed as an iterable object, which can be used either directly or for other reprocessing purposes. For example, methods such as zip () can fully accept parameters of type range.
> for i in zip (range (1recorder 6), range (2)): > print (I, end= ") (1,2) (3,4) (5,6)
In other words, the range () method, as a primary producer, produces raw materials that are of great use, and it is undoubtedly superfluous to turn it into an iterator early on.
Do you think this interpretation is reasonable? Welcome to discuss with me on this topic.
3. What is the type of range?
This is one of my answers to why range () doesn't produce iterators. Following this line of thinking, I studied the range object it produced, and found that the range object was not simple either.
The first strange thing is that it turns out to be an immutable sequence! I never noticed that. Although I never wanted to change the value of range (), I was surprised by this immutable feature.
Looking through the document, the official division is this clear-there are three basic sequence types: list, tuple, and range object. (There are three basic sequence types: lists, tuples, and range objects.)
I haven't noticed that the range type is the same basic sequence as lists and tuples! I always remember that strings are immutable sequence types. I never thought that there is an immutable sequence type here.
What is the difference between range sequence and other sequence types?
There are 12 operations supported by normal sequences. Only 10 of them are supported by range sequences, and addition splicing and multiplication repetition are not supported.
> range (2) + range (3)-- TypeError Traceback (most recent call last)... TypeError: unsupported operand type (s) for +: 'range' and' range' > range (2) * 2muri- -TypeError Traceback (most recent call last)... TypeError: unsupported operand type (s) for *: 'range' and' int'
So the question is: also immutable sequences, why do strings and tuples support these two operations, but not range sequences? Although immutable sequences cannot be modified directly, we can copy them to new sequences for operation. Why can't range objects even support this?
Let's take a look at the explanation of 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 violate that pattern.
The reason is that range objects only represent a sequence that follows a strict pattern, which is usually broken by repetition and splicing.
The crux of the problem lies in the pattern of the range sequence. If you think about it, it actually represents an arithmetic sequence. Concatenating two arithmetic sequences, or repeatedly concatenating one arithmetic sequence, it is really inappropriate to think about it, which is why the range type does not support these two operations. From this, it is inferred that other modification actions will also destroy the structure of the arithmetic sequence, so they will not be modified at all.
4. Summary
Reviewing the full text, I have come to two unpopular conclusions: range is an iterable object rather than an iterator, and range objects are immutable isometric sequences.
If you just look at the conclusion, you may not feel it, or you may say it's no big deal. But if I ask, why isn't range an iterator, and why is range an immutable sequence? Can you come up with a self-justifiable design idea for these two questions? (PS: I've decided that if I have a chance to interview someone, I need to ask these two questions.
Because of the subtle and interesting nature of the range object, I think this article is worth it. This article is written as part of a series of articles on iterators, so there is not much introduction to the basic knowledge of iterators. in addition, there is a special kind of iterator that is worth writing separately, and that is generator.
Attached: the history of Python's range () function
Although range () in Python 2 and range () in Python 3 may share a name, they are completely different animals. In fact, range () in Python 3 is just a renamed version of a function called xrange in Python 2.
Initially, both range () and xrange () generate numbers that can be iterated through with a for loop, but the former generates a list of all these numbers at once, while the latter lazily generates numbers, which means returning one number at a time when needed.
Suspending large lists takes up memory, so it's not surprising that xrange () replaces range (), name, and everything. You can read more about this decision and the background of xrange () vs range () in PEP 3100.
Note: PEP represents Python enhancement recommendations. Pep is a document that covers a wide range of topics, including proposed new features, styles, governance, and philosophy.
There are many. PEP 1 explains how they work and is a good place to start.
At this point, I believe you have a deeper understanding of "what are the basic uses of the range function in Python?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.