Is there a better way to iterate over two lists, getting one element from each list for each iteration?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 Is There A Better Way To Iterate Over Two Lists, Getting One Element From Each List For Each Iterati
00:36 Accepted Answer Score 308
00:45 Answer 2 Score 7
01:10 Answer 3 Score 22
01:35 Answer 4 Score 53
02:03 Thank you
--
Full question
https://stackoverflow.com/questions/1919...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #iteration
#avk47
ACCEPTED ANSWER
Score 308
This is as pythonic as you can get:
for lat, long in zip(Latitudes, Longitudes):
print(lat, long)
ANSWER 2
Score 53
Another way to do this would be to by using map.
>>> a
[1, 2, 3]
>>> b
[4, 5, 6]
>>> for i,j in map(None,a,b):
... print i,j
...
1 4
2 5
3 6
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:
>>> a
[1, 2, 3, 9]
>>> b
[4, 5, 6]
>>> for i,j in zip(a,b):
... print i,j
...
1 4
2 5
3 6
Using map on same data:
>>> for i,j in map(None,a,b):
... print i,j
...
1 4
2 5
3 6
9 None
ANSWER 3
Score 22
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 an izip 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 like izip.
ANSWER 4
Score 7
Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True
[Example is taken from pydocs]
In your case, it will be simply:
for (lat, lon) in zip(latitudes, longitudes):
... process lat and lon