Iterators & List Comprehensions Flashcards
Python Data Science Toolbox (Part 2) (18 cards)
iterable
object that can return an iterator
iterator
object that keeps state and produces the next value after calling next()
2 ways to iterate over iterable
- for loop
2. iter(iterable) and then next(iter(iterable))
a couple iterables that are not lists
strings and range() function
enumerate()
returns enumerate object (iterator) - series of index-value pair tuples
zip()
zips multiple lists into a zip object (similar to list of tuples)
how to unzip
- for loop
2. *zip(x, y) - unpacks iterable into positional arguments in a function call
one good use of iterators
processing data in chunks
pd.read_csv arguments
(‘.csv file’, chunksize=x)
list comprehension format
[output expression for iterator variable in iterable if predicate expression]
list comprehensions and iterables
list comps can be built over iterables
nested list comprehension
[[output expression] for iterator variable in iterable]
if/else list comprehension
[x if … else … for x in list]
dict comprehension format
{key: output expression for key in iterable}
generator
looks like a list comp but with () instead of [] and creates a generator object
iterating over a dictionary
use dictionary.items()
how to build a generator function
use “yield” instead of “return”
generating a DataFrame from a list of dicts
this is easy, just use pandas.DataFrame(list of dicts)