Programmer's Python Data - Iterables
Written by Mike James   
Monday, 15 May 2023
Article Index
Programmer's Python Data - Iterables
Sequences Are Iterables
The Iter Function

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

pythondata360Contents

  1. Python – A Lightning Tour
  2. The Basic Data Type – Numbers
       Extract: Bignum
  3. Truthy & Falsey
  4. Dates & Times
       Extract Naive Dates ***NEW!!!
  5. Sequences, Lists & Tuples
       Extract Sequences 
  6. Strings
       Extract Unicode Strings
  7. Regular Expressions
  8. The Dictionary
       Extract The Dictionary 
  9. Iterables, Sets & Generators
       Extract  Iterables 
  10. Comprehensions
       Extract  Comprehensions 
  11. Data Structures & Collections
       Extract Stacks, Queues and Deques
      
    Extract Named Tuples and Counters
  12. Bits & Bit Manipulation
       Extract Bits and BigNum 
  13. Bytes
       Extract Bytes And Strings
       Extract Byte Manipulation 
  14. Binary Files
  15. Text Files
  16. Creating Custom Data Classes
        Extract A Custom Data Class 
  17. 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

espbook

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner



Last Updated ( Monday, 15 May 2023 )