[ SRE_ARENA ]
ITERATORS & GENERATORS

Handling Massive Data.

Implementation Code: 1. Iterators & Iterables
PYTHON
my_list = ["apple", "banana", "cherry"]

# Get the iterator object from the iterable
my_it = iter(my_list)

print(next(my_it)) # apple
print(next(my_it)) # banana
print(next(my_it)) # cherry

# Strings are also iterable!
char_it = iter("SRE")
print(next(char_it)) # S
DOWNLOADING CONCEPT: 1. ITERATORS & ITERABLES...
  • ↳An iterator is an object that contains a countable number of values.
  • ↳It is an object that can be iterated upon, meaning that you can traverse through all the values.
  • ↳Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
  • ↳Lists, tuples, dictionaries, and sets are all iterable objects.
  • ↳They are iterable containers which you can get an iterator from.
  • ↳All these objects have a iter() method which is used to get an iterator.
▲ LIVE INCIDENTYou need to generate an infinite stream of sequential IDs without running out of memory.
sre@arena:~/python-iterators
sre@arena:~$ python -c "def id_gen():\n i=0\n while True: yield i; i+=1\ng=id_gen()\nprint(next(g), next(g))"