

To deal with sequences with an odd number of elements, the suggestion has been to augment the original sequence adding one element ( None) that gets paired with the previous last element, something that can be achieved with itertools.izip_longest(). It took me a moment to grok that the first answer uses two iterators while the second uses a single one. Most efficient and very pythonic: pairs = izip(** 2) Most pythonic and very efficient: pairs = izip(t, t) I added these two suggestions from the answers to the tests: def pairwise( t): Which would be the right way to ensure that all elements are included? Note that if the list has an odd number of elements then the last one will not be in any of the pairs. Is there another, “better” way of traversing a list in pairs?

It’s a result both comforting and unexpected. If I’m interpreting them correctly, that should mean that the implementation of lists, list indexing, and list slicing in Python is very efficient. Return izip(islice(t, None, None, 2), islice(t, 1, None, 2))įor f in pairs_1, pairs_2, pairs_3, pairs_4: Lets call the zip () function and pass in L1 and L2 as arguments.

As a first example, lets pick two lists L1 and L2 that contain 5 items each.
IZIP PYTHON 3 HOW TO
I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests: import timeĭef pairs_1( t): return zip(t, t)ĭef pairs_2( t): return izip(t, t)ĭef pairs_3( t): return izip(islice(t, None, None, 2), islice(t, 1, None, 2)) How to Use Pythons zip () Function Try it Yourself Try running the following examples in your favorite IDE. I was wondering which would be the pythonic and efficient way to do it, and found this on Google: pairs = zip(t, t) Often enough, I’ve found the need to process a list by pairs.
