0

I have 2 lists: latitude and longitude, which I'd like to format into an object in the following format:

coordinates = (-33.89419, 151.19449), (-33.66061, 151.25468), ...

How do I go about formatting this? It has to be the first latitude item with the first longitude items, and so forth. Thank you.

latitude 
 -33.89419,
 -33.66061,
 -33.89875

longitude
151.19449,
 151.25468,
 151.28507,
 151.21634

Many thanks.

2
  • Sort of. I'm not sure how to apply zip. It gives me: '-33.92664151.25075', '-33.89419151.19449', not (-33.89419, 151.19449), ... Commented May 7, 2021 at 4:48
  • zip doesn't give you that, the answer that formats its results into a string does that. zip actually gives you tuples of the exact form requested, you just stringify them one by one and you get the desired result, e.g. ', '.join(str(pair) for pair in zip(latitude, longitude)) if you want a string, or just list(zip(latitude, longitude)) if you want a list of tuple pairs. Commented May 7, 2021 at 5:04

2 Answers 2

0

You can combine both the latitude and longitude lists into a single list element-wise using zip. To get to the format that you wanted you can do the following

>>> str(list(zip(a,b)))[1:-1]
'(-33.89419, 151.19449), (-33.66061, 151.25468), (-33.89875, 151.28507)'
Sign up to request clarification or add additional context in comments.

2 Comments

While using this, one must note that zip object is not subscriptable. You would always need to convert zip object to a list or tuple for accessing items
@CoolCoder: Or just loop over it and use elements one at a time. Or unpack it to a varargs function (technically converts to tuple); a reasonable alternative if you're printing here would be print(*zip(a, b), sep=", ") (which avoids the need for slicing to strip off the list repr's brackets too.
0

You can do:

coordinates = []
for x in range(len(latitude)):
    coordinates.append([latitude[x], longitude[x]])

Note: It has been assumed that the number of latitude coordinates is same as the number of longitude coordinates.

1 Comment

zip is definitely the more Pythonic way to go here. Iterating over ranges and indexing is both surprisingly slow and error-prone (e.g. in this case, where you just have to assume the lists are the same length, rather than stopping early as in zip, or providing a filler value, as in itertools.zip_longest). This is basically a verbose, slower, more fragile version of coordinates = list(zip(latitude, longitude))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.