|
| 1 | +Not using ``zip()`` to iterate over a pair of lists |
| 2 | +=================================================== |
| 3 | + |
| 4 | +Summary |
| 5 | +------- |
| 6 | + |
| 7 | +``zip()`` is the preferred way to iterate through a pair of lists. Although there are other valid ways to iterate through a pair of lists, this is the most concise way, and in general you can improve code readability by using the method which is most familiar to the most Python programmers. |
| 8 | + |
| 9 | +Description |
| 10 | +----------- |
| 11 | + |
| 12 | +`PEP 20 <http://legacy.python.org/dev/peps/pep-0020/>`_ states "There should be one-- and preferably only one --obvious way to do it." The preferred way to iterate through a pair of lists is to declare two variables in a loop expression, and then call ``zip(list_one, list_two)``, where ``list_one`` and ``list_two`` are the two lists you wish to iterate through. For each loop iteration, Python will automatically assign the first variable as the next value in the first list, and the second variable as the next value in the second list. |
| 13 | + |
| 14 | +Examples |
| 15 | +---------- |
| 16 | + |
| 17 | +For loop does not use ``zip()`` to iterate through a pair of lists |
| 18 | +.................................................................. |
| 19 | + |
| 20 | +The module below defines a variable ``i`` which serves as an index variable for iterating through two lists. Within the for loop the module accesses the corresponding value for each list by using the index variable. This is a common way for iterating through two lists, but it is not the preferred way in python. |
| 21 | + |
| 22 | +.. warning:: The code below is an example of an error. Using this code will create bugs in your programs! |
| 23 | + |
| 24 | +.. code:: python |
| 25 | +
|
| 26 | + numbers = [1, 2, 3] |
| 27 | + letters = ["A", "B", "C"] |
| 28 | +
|
| 29 | + for index in range(numbers): |
| 30 | + print numbers[index], letters[index] |
| 31 | +
|
| 32 | +Solutions |
| 33 | +--------- |
| 34 | + |
| 35 | +Use ``zip()`` to iterate through a pair of lists |
| 36 | +................................................ |
| 37 | + |
| 38 | +The updated module below demonstrates the Pythonic style for iterating through a pair of lists. When the module defines two variables in its ``for`` loop in conjunction with a call to ``zip(numbers, letters)`` on the pair of lists, Python automatically assigns the first variable as the next value in the first list, and the second variable as the next value in the second list. |
| 39 | + |
| 40 | +.. code:: python |
| 41 | +
|
| 42 | + numbers = [1, 2, 3] |
| 43 | + letters = ["A", "B", "C"] |
| 44 | +
|
| 45 | + for numbers_value, letters_value in zip(numbers, letters): |
| 46 | + print numbers_value, letters_value |
| 47 | + |
| 48 | +References |
| 49 | +---------- |
| 50 | +- `PEP 20 - The Zen of Python <http://legacy.python.org/dev/peps/pep-0020/>`_ |
0 commit comments