pub-3785248829033902 | Python: Iterators, Iteration, Iterator, Iterable | - Big data with Python

| Python: Iterators, Iteration, Iterator, Iterable |

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.


Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.

Loopings:
#looping over a list
for i in 'Big Data':
    print(i)
#looping over characters
for i in range(0,3):
    print(i)
#looping over a dictionary
for i in {'Y':1, 'o':2}:
    print(i)


In Python, iterable and iterator have specific meanings.

An ITERABLE is:

-anything that can be looped over (i.e. you can loop over a string or file) or
-anything that can appear on the right-side of a for-loop:  for x in iterable: ... or
-anything you can call with iter() that will return an ITERATOR:  iter(obj) or
-an object that defines __iter__ that returns a fresh ITERATOR, or it may have a __getitem__ method -suitable for indexed lookup.

An ITERATOR is an object:

-with state that remembers where it is during iteration,
-with a __next__ method that:
-returns the next value in the iteration
-updates the state to point at the next value
-signals when it is done by raising StopIteration
-and that is self-iterable (meaning that it has an __iter__ method that returns self).

The best way to learn new things is to take a practical approach of the things you want to learn. Here is a fragment of code that demonstrates how to build a Iteration  statement in Python:

Æ’ python command

num = [1, 2, 5, 10]
abc = ['python', 'big data']

for i in num:
    print(i)

for k in abc:
    print(k)

output

1
2
5
10

python
big data


Previous
Next Post »