This question already has an answer here:
I have a list of Latitudes and one of Longitudes and need to iterate over the latitude and longitude pairs.
Is it better to:
A. Assume that the lists are of equal lengths:
for i in range(len(Latitudes): Lat,Long=(Latitudes[i],Longitudes[i])
B. Or:
for Lat,Long in [(x,y) for x in Latitudes for y in Longitudes]:
(Note that B is incorrect. This gives me all the pairs, equivalent to itertools.product()
)
Any thoughts on the relative merits of each, or which is more pythonic?
This post helped me with
zip()
. I know I'm a few years late, but I still want to contribute. This is in Python 3.Note: in python 2.x,
zip()
returns a list of tuples; in Python 3.x,zip()
returns an iterator.itertools.izip()
in python 2.x ==zip()
in python 3.xSince it looks like you're building a list of tuples, the following code is the most pythonic way of trying to accomplish what you are doing.
Or, alternatively, you can use
list comprehensions
(orlist comps
) should you need more complicated operations. List comprehensions also run about as fast asmap()
, give or take a few nanoseconds, and are becoming the new norm for what is considered Pythonic versusmap()
.in case your Latitude and Longitude lists are large and lazily loaded:
or if you want to avoid the for-loop
Another way to do this would be to by using
map
.One difference in using map compared to zip is, with zip the length of new list is
same as the length of shortest list. For example:
Using map on same data:
Good to see lots of love for
zip
in the answers here.However it should be noted that if you are using a python version before 3.0, the
itertools
module in the standard library contains anizip
function which returns an iterable, which is more appropriate in this case (especially if your list of latt/longs is quite long).In python 3 and later
zip
behaves likeizip
.Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.
[Example is taken from pydocs]
In your case, it will be simply: