views:

395

answers:

6

I have a list of Latitudes and one of Longitudes and need to iterate over the latitude and longitude pairs.

Do you think it's be better to:

A) (assume that equal lengths is already checked)

for i in range(len(Latitudes):
  Lat,Long=(Latitudes[i],Longitudes[i])

*** EDIT .... or, B)

for Lat,Long in [(x,y) for x in Latitudes for y in Longitudes]:
  ....

**** EDIT (12/17) Note that B is incorrect. This gives me all the pairs, equivalent to itertools.product()

Any thoughts on the relative merits of each. I'm still getting in the hang of being "pythonic"

+16  A: 

This is as pythonic as you can get:

for lat, long in zip(Latitudes, Longitudes):
    print lat, long
Roberto Bonvallet
In Python 2.x you might consider itertools.izip instead (zip does the same thing in Python 3.x).
Nicholas Riley
+2  A: 

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 (latitudes, longitudes):
    ... process lat and lon
notnoop
+1  A: 
for Lat,Long in zip(Latitudes, Longitudes):
gnibbler
+5  A: 

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.

Wogan
+2  A: 
sateesh
+1  A: 

in case your Latitude and Longitude lists are large and lazily loaded:

from itertools import izip
for lat, lon in izip(latitudes, longitudes):
    process(lat, lon)

or if you want to avoid the for-loop

from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))
JudoWill