Tutorial by Examples

An iterable is an object that can return an iterator. Any object with state that has an __iter__ method and returns an iterator is an iterable. It may also be an object without state that implements a __getitem__ method. - The method can take indices (starting from zero) and raise an IndexError whe...
Iterable can be anything for which items are received one by one, forward only. Built-in Python collections are iterable: [1, 2, 3] # list, iterate over items (1, 2, 3) # tuple {1, 2, 3} # set {1: 2, 3: 4} # dict, iterate over keys Generators return iterables: def foo(): # foo ...
s = {1, 2, 3} # get every element in s for a in s: print a # prints 1, then 2, then 3 # copy into list l1 = list(s) # l1 = [1, 2, 3] # use list comprehension l2 = [a * 2 for a in s if a > 2] # l2 = [6]
Use unpacking to extract the first element and ensure it's the only one: a, = iterable def foo(): yield 1 a, = foo() # a = 1 nums = [1, 2, 3] a, = nums # ValueError: too many values to unpack
Start with iter() built-in to get iterator over iterable and use next() to get elements one by one until StopIteration is raised signifying the end: s = {1, 2} # or list or generator or even iterator i = iter(s) # get iterator a = next(i) # a = 1 b = next(i) # b = 2 c = next(i) # raises S...
def gen(): yield 1 iterable = gen() for a in iterable: print a # What was the first item of iterable? No way to get it now. # Only to get a new iterator gen()

Page 1 of 1