Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Thursday, May 3, 2012

Itertools izip and izip_longest method explained

Itertools izip makes an iterator that aggregates elements from each of the iterables. Caution: it only zips elements for the length of the shortest passed iterable. As you can see 'Demi Moore' is skipped !!
import itertools

fName = ['Adam', 'Liam', 'Bruce', 'Kate', 'Demi']
lName = ['Sandler', 'Neeson', 'Willis', 'Winslet', 'Moore']
sex =  [1, 1, 1, 0]

zipped_shortest = itertools.izip(fName, lName, sex)
print list(zipped_shortest)

zipped_longest = itertools.izip_longest(fName, lName, sex)
print list(zipped_longest)

[('Adam', 'Sandler', 1), ('Liam', 'Neeson', 1), ('Bruce', 'Willis', 1), ('Kate', 'Winslet', 0)]
[('Adam', 'Sandler', 1), ('Liam', 'Neeson', 1), ('Bruce', 'Willis', 1), 
 ('Kate', 'Winslet', 0), ('Demi', 'Moore', None)]

No comments:

Post a Comment