How do I iterate through two lists in parallel?
Python 3
for f, b in zip(foo, bar):
print(f, b)
zip
stops when the shorter of foo
or bar
stops.
In Python 3, zip
returns an iterator of tuples, like itertools.izip
in Python2. To get a list
of tuples, use list(zip(foo, bar))
. And to zip until both iterators are
exhausted, you would use
itertools.zip_longest.
Python 2
In Python 2, zip
returns a list of tuples. This is fine when foo
and bar
are not massive. If they are both massive then forming zip(foo,bar)
is an unnecessarily massive
temporary variable, and should be replaced by itertools.izip
oritertools.izip_longest
, which returns an iterator instead of a list.
import itertools
for f,b in itertools.izip(foo,bar):
print(f,b)
for f,b in itertools.izip_longest(foo,bar):
print(f,b)
izip
stops when either foo
or bar
is exhausted.izip_longest
stops when both foo
and bar
are exhausted.
When the shorter iterator(s) are exhausted, izip_longest
yields a tuple with None
in the position corresponding to that iterator. You can also set a different fillvalue
besides None
if you wish. See here for the full story.
Note also that zip
and its zip
-like brethen can accept an arbitrary number of iterables as arguments. For example,
for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'],
['red', 'blue', 'green']):
print('{} {} {}'.format(num, color, cheese))
prints
1 red manchego
2 blue stilton
3 green brie
How do I loop through a list by twos?
You can use a range
with a step size of 2:
Python 2
for i in xrange(0,10,2):
print(i)
Python 3
for i in range(0,10,2):
print(i)
Note: Use xrange
in Python 2 instead of range
because it is more efficient as it generates an iterable object, and not the whole list.
Is there a better way to iterate over two lists, getting one element from each list for each iteration?
This is as pythonic as you can get:
for lat, long in zip(Latitudes, Longitudes):
print(lat, long)
Iterating over every two elements in a list
You need a pairwise()
(or grouped()
) implementation.
def pairwise(iterable):
"s -> (s0, s1), (s2, s3), (s4, s5), ..."
a = iter(iterable)
return zip(a, a)
for x, y in pairwise(l):
print("%d + %d = %d" % (x, y, x + y))
Or, more generally:
def grouped(iterable, n):
"s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
return zip(*[iter(iterable)]*n)
for x, y in grouped(l, 2):
print("%d + %d = %d" % (x, y, x + y))
In Python 2, you should import izip
as a replacement for Python 3's built-in zip()
function.
All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.
N.B: This should not be confused with the pairwise
recipe in Python's own itertools
documentation, which yields s -> (s0, s1), (s1, s2), (s2, s3), ...
, as pointed out by @lazyr in the comments.
Little addition for those who would like to do type checking with mypy on Python 3:
from typing import Iterable, Tuple, TypeVar
T = TypeVar("T")
def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]:
"""s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ..."""
return zip(*[iter(iterable)] * n)
Iterating over two lists one after another
This can be done with itertools.chain
:
import itertools
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
for i in itertools.chain(l1, l2):
print(i, end=" ")
Which will print:
1 2 3 4 5 6 7 8
As per the documentation, chain
does the following:
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.
If you have your lists in a list, itertools.chain.from_iterable
is available:
l = [l1, l2]
for i in itertools.chain.from_iterable(l):
print(i, end=" ")
Which yields the same result.
If you don't want to import a module for this, writing a function for it is pretty straight-forward:
def custom_chain(*it):
for iterab in it:
yield from iterab
This requires Python 3, for Python 2, just yield
them back using a loop:
def custom_chain(*it):
for iterab in it:
for val in iterab:
yield val
In addition to the previous, Python 3.5
with its extended unpacking generalizations, also allows unpacking in the list literal:
for i in [*l1, *l2]:
print(i, end=" ")
though this is slightly faster than l1 + l2
it still constructs a list which is then tossed; only go for it as a final solution.
For loop iterating through two lists python
i assume that you have the same list length for list1 and list 2
in order to print it you just need to specify the position of the index on list like list[index], this will print the list value.
list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]
for i in range(len(list1)):
print(f"{list1[i]}, {list2[i]}")
How to iterate over a list two at a time in Python 3?
You can use range like this by using step (indexing):
list_1 = [1,3,2,4,3,1,2,7]
for i in range(0,len(list_1),2):
print(list_1[i])
or just using python slice notation:
list_1 = [1,3,2,4,3,1,2,7]
for v in list_1[::2]:
print(v)
Iterate through pairs of items in a Python list
From the itertools
recipes:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for v, w in pairwise(a):
...
Loop through Python list with 2 variables
Here's an example how you can do it. Take second index as function of length minus index minus one:
l = [1, 2, 3, 4]
for i, _ in enumerate(l):
print(l[i], l[len(l)-i-1])
This will output
(1, 4)
(2, 3)
(3, 2)
(4, 1)
Not printing indexes themselves, but you can print them, if you chose to do so.
Related Topics
Convert a 1D Array to a 2D Array in Numpy
MySQL "Incorrect String Value" Error When Save Unicode String in Django
How to Load/Edit/Run/Save Text Files (.Py) into an Ipython Notebook Cell
How to Replace Back Slash Character with Empty String in Python
Getting Values from JSON Using Python
Python: Catching Specific Exception
Typeerror: 'Range' Object Does Not Support Item Assignment
Comments Not Working in Jinja2
My Py2App App Will Not Open. What's the Problem
In Python, How Does One Catch Warnings as If They Were Exceptions
How to Print the Key-Value Pairs of a Dictionary in Python
Python: Tf-Idf-Cosine: to Find Document Similarity
How to Grab Number After Word in Python
Numpy: Fix Array with Rows of Different Lengths by Filling the Empty Elements with Zeros
Python How to Read N Number of Lines at a Time