Powerful Python
Aaron Maxwell
iter()
numbers = [1, 2, 3] iterator_object = iter(numbers) print(next(iterator_object)) # 1 print(next(iterator_object)) # 2 print(next(iterator_object)) # 3 print(next(iterator_object)) # StopIteration # You can also use a for loop for n in numbers: print(n) print(sum(numbers)) # 6
You don't normally call iter()
directly. Instead, you use a for loop, and Python calls it for you.
Generators are a useful shortcut for creating iterators. Generators have a smaller memory footprint than lists because they don't store all the values at once.
def generator_function(): n = 1 while n < 4: yield n n += 1 generator_object = generator_function() print(next(generator_object)) # 1 print(next(generator_object)) # 2 print(next(generator_object)) # 3 print(next(generator_object)) # StopIteration # You can also use a for loop for n in generator_function(): print(n) print(sum(generator_function())) # 6
range
, dict.keys
, dict.values
, map
, filter
, zip
, and enumerate
return objects that are like generators in that they produce values on demand instead of storing them all in memory at once.
You can think of class methods as alternative constructors.
class Money: def __init__(self, dollars, cents): self.dollars = dollars self.cents = cents @classmethod def from_pennies(cls, total_cents): dollars = total_cents // 100 cents = total_cents % 100 return cls(dollars, cents) piggie_bank_cash = Money.from_pennies(3217) print(type(piggie_bank_cash)) # <class '__main__.Money'> print(piggie_bank_cash.dollars) # 32 print(piggie_bank_cash.cents) # 17
Get this book on Amazon.