Kalil de Lima - Python Meetup
https://github.com/kaozdl
kalil.de.lima@fing.edu.uy
kalil@rootstrap.com
An iterable is an object that represents a collection of data. Such collection should be able to provide his elements one at a time.
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
#Now we can iterate with this
for x in myiter:
print(x)
#Or with
for x in MyNumbers():
print(x)This defines an iterator with the following advantages:
#All the even natural numbers
def all_even():
n = 0
while True:
yield n
n += 2
#Circular lists
def circular(start, end):
current = start
while True:
yield current
if current == end:
current = start
else:
current += 1
#A nice alternative to map
squares = (x*x for x in values)
#Useful for filtering
even_squares = (x*x for x in values if x % 2 == 0)
#Can be iterated right away
for address in (a in addresses if 'wes' in a):
print(address)
#Can be fed to builtins right away
{ x: x*x for x in values }Even tough is not released yet, Python 3.8 introduces assignment expressions, which can be used inside generator expressions to improve the readability and memoize function calls
#Now
some_list = [
generate_expensive_element(value)
for value in some_iterable
if meets_condition(generate_expensive_element(value))
]
#In python 3.8
some_list = [
(elem := generate_expensive_element(value)) #Element gets memoized
for value in some_iterable
if meets_condition(elem)
]All code examples are available at:
https://github.com/kaozdl/python_meetup