itertools Flashcards
count()
an infinite interator
counter = itertools.count()
for num in counter:
if num > 10:
break
print(num)
To use the itertools methods what is required?
import itertools
What does this return, if the preceding counter was 12?
print(next(counter)
13 or the next value in the counter.
What does this return?
data = [100, 200, 300, 400]
daily_data = list(zip(itertools.count(), data))
daily_data
[(0, 100), (1, 200), (2, 300), (3, 400)]
What does this return?
data = [100, 200, 300, 400]
daily_data = list(enumerate(data))
daily_data
the same result as itertools.count()
[(0, 100), (1, 200), (2, 300), (3, 400)]
Provide the values returned If given
counter = itertools.count(start=5, step=5)
print(next(counter))
print(next(counter))
print(next(counter))
print(next(counter))
5
10
15
20
Why won’t this zip method return 10 values?
data = [100, 200, 300, 400]
daily_data = list(zip(range(10), data))
daily_data
[(0, 100), (1, 200), (2, 300), (3, 400)]
Because the zip() is exhausted by the data, only four values being inputed.
What would be the outcome of this if itertool.zip_longest() was utilized instead of zip()?
data = [100, 200, 300, 400]
daily_data = list(zip(range(10), data))
daily_data
[(0, 100), (1, 200), (2, 300), (3, 400)]
Full range would be outputed with None values for those that do not have a subsequent match
[(0, 100), (1, 200), (2, 300), (3, 400), (4, None), (5, None), (6, None), (7, None), (8, None), (9, None)]
cycle()
An Infinite iterator
counter = itertools.cycle([1,2,3])
print(next(counter)) #1
print(next(counter)) #2
print(next(counter)) #3
print(next(counter)) #1
print(next(counter)) #2
What is this cycle() mimicing?
counter = itertools.cycle((‘On’, ‘Off’))
an on off toggle switch, value is either on or off.
repeat()
Infinite iterator
counter = itertools.repeat(2, times= 3)
print(next(counter)) #2
print(next(counter)) #2
print(next(counter)) #2
print(next(counter)) Traceback (most recent call last) StopIteration
What is the output?
squares = map(pow, range(10), itertools.repeat(2))
print(list(squares))
0-9 squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
What is the ouput?
squares = itertools.starmap(pow, [(2,5), (3,2), (10,3)])
2 to the 5th = 32
3 squared = 9
10 cubed = 1000
combinations()
Combinatoric iterator
order does not matter
letters = [‘a’, ‘b’, ‘c’, ‘d’]
result = itertools.combinations(letters, 2)
for item in result:
print(item)
permutations()
Combinatoric iterator
good for racing events where order matters
letters = [‘a’, ‘b’, ‘c’, ‘d’]
for item in itertools.permutations(letters, 2):
print(item)