Python Flashcards
Iterable vs Iterator
Python
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).
7 // 2
What does above expression evaluate to?
Python
3
floor division - divides and rounds down to nearest int
How to access idx and element in for loop
Python
for idx, element in enumerate(elements): print(idx, element)
for loop using range
Python
for x in range(6): print(x)