Home > database >  How to append lists to an empty list to get a list of lists?
How to append lists to an empty list to get a list of lists?

Time:10-29

Yes, this question has been addressed many times here, but I can't find a solution to my specific use case.

I have a function that hands back a tuple of latitude/longitude coordinates. I'd like to:

  1. prepend a city name to this tuple
  2. create a list out of #1
  3. append this list to an empty list
  4. repeat for each time the function is run

For example:

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent = 'MyApp')

cities_list = ['New York', 'Los Angeles', 'Houston']

for city in cities_list:
    
    temp_list = []
    
    city_coordinates = geolocator.geocode(city)
    
    latitude = city_coordinates.latitude
    longitude = city_coordinates.longitude
    
    list_element = list(city, latitude, longitude)
       
    temp_list.append(list_element)

temp_list

TypeError: list expected at most 1 argument, got 3

This is what I'd like temp_list to look like:

[['New York', 40.7127281, -74.0060152], ['Los Angeles', 34.0536909, -118.242766], ['Houston', 29.7589382, -95.3676974]]

How would I do this?

Thanks!

CodePudding user response:

Your for loop is not right.

temp_list = []

for city in cities_list:
    
    city_coordinates = geolocator.geocode(city)
    
    latitude = city_coordinates.latitude
    longitude = city_coordinates.longitude
    temp_list.append([city, latitude, longitude])

CodePudding user response:

Even if it is not your direct question, you are building a list by consistently appending to an empty list. Nothing really bad but it is not the Pythonic way. It is more efficient (hence more Pythonic) to build the list as a comprehension:

temp_list = [ [city]   list(geolocator.geocode(city)) for city in cities_list]

or even better (thank to juanpa.arrivillaga):

temp_list = [ [city, *geolocator.geocode(city)] for city in cities_list]

It is not always possible but it is here, because you can convert a tuple into a list with list and concatenate two lists with .

CodePudding user response:

This line

list_element = list(city, latitude, longitude)

could simply be

list_element = [city, latitude, longitude]

Otherwise to initialize a list you'd need a single iterable, for example passing a tuple

list_element = list((city, latitude, longitude))

but at that point it is more idiomatic to just construct using the literal list syntax from above.

  • Related