Iterators & List Comprehensions Flashcards

Python Data Science Toolbox (Part 2)

1
Q

iterable

A

object that can return an iterator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

iterator

A

object that keeps state and produces the next value after calling next()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

2 ways to iterate over iterable

A
  1. for loop

2. iter(iterable) and then next(iter(iterable))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

a couple iterables that are not lists

A

strings and range() function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

enumerate()

A

returns enumerate object (iterator) - series of index-value pair tuples

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

zip()

A

zips multiple lists into a zip object (similar to list of tuples)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

how to unzip

A
  1. for loop

2. *zip(x, y) - unpacks iterable into positional arguments in a function call

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

one good use of iterators

A

processing data in chunks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

pd.read_csv arguments

A

(‘.csv file’, chunksize=x)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

list comprehension format

A

[output expression for iterator variable in iterable if predicate expression]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

list comprehensions and iterables

A

list comps can be built over iterables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

nested list comprehension

A

[[output expression] for iterator variable in iterable]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

if/else list comprehension

A

[x if … else … for x in list]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

dict comprehension format

A

{key: output expression for key in iterable}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

generator

A

looks like a list comp but with () instead of [] and creates a generator object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

iterating over a dictionary

A

use dictionary.items()

17
Q

how to build a generator function

A

use “yield” instead of “return”

18
Q

generating a DataFrame from a list of dicts

A

this is easy, just use pandas.DataFrame(list of dicts)