Page 3 of 3
The Iter Function
If you need to get an iterator from an iterable then it is better to use the built-in function iter() rather than the __iter__ method which is intended to be internal. One advantage is that if the object doesn’t support the iterable protocol the TypeError exception is raised. In the previous example of using an iterator as an iterable it would be better to use iter():
numbers=randIt()
numberIterator=iter(numbers)
for x in numberIterator:
print(x)
A second advantage is that iter() will return an iterator if the object doesn’t have an __iter__ method defined but supports the sequence __getitem__ method using an integer argument starting from zero. That is, if you call __iter__ directly and it doesn’t exist you will generate an exception, but if you call iter in the same situation and a suitable __getitem__ exists you will return a system constructed iterator.
If you supply a second argument to the iter function it behaves in a slightly different way. The call:
iter(function,sentinel)
returns an iterator which is constructed by the system to call the supplied function on each call to __next__ until the return value equals the sentinel or flag value that is used to signify when to terminate the iteration. You can see that this is just a way of implementing a conditional for loop and as such not really part of the iterable philosophy. Consider, for example:
i=0
def count():
global i
i=i+1
return i
for x in iter(count,10):
print(x)
The function increments the global variable i on each call and returns the result. Using this in the iter function with a sentinel of 10 results in it being called for values from 1 to 9 and then it stops when its value equals the sentinel value of 10. In a more general context, the function would obtain the data for the __next__ value which would be equal to the sentinel when there was no more data. For example, you could process a file using a for loop via a function that read in data until there was no more. This sort of approach is probably best avoided in favor of more obvious approaches.
In chapter but not in this extract
- The Set
- Making New Sets From Sets
- Set Tests
- Enumerators
- Generators
- Generators As Coroutines
Summary
-
Iterables are simply collections that you can step through one item at a time without necessarily being able to use an index to access a particular element.
-
Iterables are mostly used in for loops, but they are also valuable in other contexts.
-
To be a true iterable, a class has to have an __iter__ method which returns an iterator for the class.
-
An iterator has a __next__ method which returns the next item in the iteration and an optional __iter__ method which makes it iterable.
-
A sequence doesn’t have to have an __iter__ method and so isn’t necessarily an iterable, but if it has a __getitem__ method that accepts an integer key starting from 0 then the system will construct an iterator for it. This allows most sequences to be used as iterables.
-
You can stop an iteration by raising the StopIteration exception.
-
To allow multiple independent iterations, the __iter__ method should return a new iterator object every time it is called.
-
The best way to get an iterator from an iterable is to use the iter function which will construct an iterator from a sequence if the __iter__ method doesn’t exist and allows a sentinel.
-
The set is the closest thing to a pure iterable in that it has no indexing or enumeration.
-
You can convert an iterable into an enumerable by using the enumerate function.
-
A generator is another way of creating an iterator. The yield instruction allows you to pause the function and restart it.
-
A generator can also act as a coroutine by assigning to the yield instruction to pass data into the paused function.
Programmer's Python Everything is Data
Is now available as a print book: Amazon
Contents
- Python – A Lightning Tour
- The Basic Data Type – Numbers
Extract: Bignum
- Truthy & Falsey
- Dates & Times
Extract Naive Dates ***NEW!!!
- Sequences, Lists & Tuples
Extract Sequences
- Strings
Extract Unicode Strings
- Regular Expressions
- The Dictionary
Extract The Dictionary
- Iterables, Sets & Generators
Extract Iterables
- Comprehensions
Extract Comprehensions
- Data Structures & Collections
Extract Stacks, Queues and Deques Extract Named Tuples and Counters
- Bits & Bit Manipulation
Extract Bits and BigNum
- Bytes
Extract Bytes And Strings Extract Byte Manipulation
- Binary Files
- Text Files
- Creating Custom Data Classes
Extract A Custom Data Class
- Python and Native Code
Extract Native Code Appendix I Python in Visual Studio Code Appendix II C Programming Using Visual Studio Code
<ASIN:1871962765>
<ASIN:1871962749>
<ASIN:1871962595>
<ASIN:B0CK71TQ17>
<ASIN:187196265X>
Related Articles
Creating The Python UI With Tkinter
Creating The Python UI With Tkinter - The Canvas Widget
The Python Dictionary
Arrays in Python
Advanced Python Arrays - Introducing NumPy
|