Help us understand the problem. What is going on with this article?

EP 11 Use `zip` to Process Iterators in Parallel

More than 3 years have passed since last update.
  • The zip built-in function can be used to iterate over multiple iterators in parallel.
  • In Python 3, zip is a lazy evaluation that produces tuples. In Python 2, zip returns the full result as a list of tuples.
  • zip truncate its outpu silently if you supply it with iterators of different length.
  • The zip_longest function from the itertools built-in module lets you iterate over multiple iterators in parallel regardless of the their lengths.

Effective Python

Verbose

>>> names = "Michel Stonbreaker Peter Bilas Franklin".split()
>>> letters = [len(n) for n in names]
>>> longest_name = None
>>> max_letters = 0
>>> for i in range(len(names)):
...  count = letters[i]
...  if count > max_letters:
...   longest_name = names[i]
...   max_letters = count
...
>>> print(longest_name)
Stonbreaker

You can use enumerate. But it is still verbose.

>>> for i, name in enumerate(names):
...  count = letters[i]
...  if count > max_letters:
...   longest_name = names[i]
...   max_letters = count
...
>>> print(longest_name)
Stonbreaker
>>> for name, count in zip(names, letters):
...  if count > max_letters:
...   longest_name = name
...   max_letters = count
...
>>> print(longest_name)
Stonbreaker

zip truncate implecitly. if it iterate the different length of iteratable objects.

itertools.zip_longest could be a solution for this.

>>> for name, count in zip(names, letters):
...     print(name, count)
...
Michel 6
Stonbreaker 11
Peter 5
Bilas 5
Franklin 8
>>> from itertools import zip_longest
>>> for name, count in zip_longest(names, letters):
...  print(name, count)
...
Michel 6
Stonbreaker 11
Peter 5
Bilas 5
Franklin 8
Matei None
>>>
giwa
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした