When a function or loop needs to process values one at a time, an iterable supplies those values sequentially. Lists, strings, tuples, dictionaries, sets, files, and range objects can serve as iterables; integers cannot. section 7.16 section 10.0
Use iterables in several common patterns:
- Pass an iterable's elements as separate function arguments with unpacking: mysum(*[1, 2, 3]). section 1.8
- Transform each element with a comprehension, whose source can be a string, list, tuple, dictionary, set, or file. section 7.16 section 7.2
- Use iterables with built-ins such as enumerate, reversed, and range, or feed them into generator expressions. section 1.17 section 10.26
Transforming and consuming an iterable
numbers = range(15) print(','.join(str(number) for number in numbers)) Here, range supplies integers one at a time, the generator expression converts each integer to a string, and join combines the results. A list comprehension could also produce the intermediate values, but the generator expression feeds them directly to sum or join. section 7.2
class LoudIterator():
def __init__(self, data):
print('\tNow in __init__')
self.data = data #1
self.index = 0 #2
def __iter__(self):
print('\tNow in __iter__')
return self #3
def __next__(self):
print('\tNow in __next__')
if self.index >= len(self.data): #4
print(
f'\tself.index ({self.index}) is too big; exiting')
raise StopIteration
value = self.data[self.index] #5
self.index += 1 #6
print('\tGot value {value}, incremented index to {self.index}')
return value
for one_item in LoudIterator('abc'):
print(one_item)
A custom iterable follows the iterator protocol: __iter__ returns an iterator, __next__ supplies the next value, and StopIteration ends the loop. section 10.0 section 10.2






