...

/

Other Fun Stuff in the itertools Module

Other Fun Stuff in the itertools Module

We'll cover the following...
Press + to interact
import itertools
print (list(itertools.product('ABC', '123'))) #①
#[('A', '1'), ('A', '2'), ('A', '3'),
# ('B', '1'), ('B', '2'), ('B', '3'),
# ('C', '1'), ('C', '2'), ('C', '3')]
print (list(itertools.combinations('ABC', 2))) #②
#[('A', 'B'), ('A', 'C'), ('B', 'C')]

① The itertools.product() function returns an iterator containing the Cartesian product of two sequences.

② The itertools.combinations() function returns an iterator containing all the possible combinations of the given sequence of the given length. This is like the itertools.permutations() function, except combinations don’t include items that are duplicates of other items in a different order. So itertools.permutations('ABC', 2) will return both ('A', 'B') and ('B', 'A') (among others), but itertools.combinations('ABC', 2) will not return ('B', 'A') because it is a duplicate of ('A', 'B') in a different order.

Press + to interact
names = list(open('favorite-people.txt', encoding='utf-8')) #①
print (names)
#['Dora\n', 'Ethan\n', 'Wesley\n', 'John\n', 'Anne\n','Mike\n', 'Chris\n', 'Sarah\n', 'Alex\n', 'Lizzie\n']
names = [name.rstrip() for name in names] #②
print (names)
#['Dora', 'Ethan', 'Wesley', 'John', 'Anne','Mike', 'Chris', 'Sarah', 'Alex', 'Lizzie']
names = sorted(names) #③
print (names)
#['Alex', 'Anne', 'Chris', 'Dora', 'Ethan','John', 'Lizzie', 'Mike', 'Sarah', 'Wesley']
names = sorted(names, key=len) #④
print (names)
#['Alex', 'Anne', 'Dora', 'John', 'Mike','Chris', 'Ethan', 'Sarah', 'Lizzie', 'Wesley']

① This idiom returns a list of the lines in a text file.

② Unfortunately (for this example), the list(open(filename)) idiom also includes the carriage returns at the end of each line. This list comprehension uses the rstrip() string method to strip ...