-1

I am SO stuck - (been trying for a day and half now - and I cannot figure out how to code this in python to get past where it cuts off at the bottom - PLEASE guide me in how to set this up for success. Thanks.

Our cities list contains information about the top 12 cities. For our upcoming iteration tasks, it will be useful to have a list of the numbers 0 through 11. Use what we know about len and rangeto generate a list of numbers 1 through 11. Assign this to a variable called city_indices.

len(cities)
range(0, len(cities))
city_indices=list(range(0,len(cities)))
city_indices
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]`

Now we want to create labels for each of the cities. We'll provide a list of the city_names for you.

city_names = ['Buenos Aires',
 'Toronto',
 'Pyeongchang',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

for index in list(range(0, len(city_names))):
    print(city_names[index])

Buenos Aires
Toronto
Pyeongchang
Marakesh
Albuquerque
Los Cabos
Greenville
Archipelago Sea
Walla Walla Valley
Salina Island
Solta
Iguazu Falls

Your task is to assign the variable names_and_ranks to a list, with each element equal to the city name and it's corresponding rank. For example, the first element would be, "1. Buenos Aires" and the second would be "2. Toronto". Use a for loop and the lists city_indices and city_names to accomplish this.

for index in [0,1,2,3,4,5,6,7,8,9,10,11]:
   print(city_indices[index]+".", city_names[index])

Error:

TypeErrorTraceback (most recent call last)
in ()
1 for index in [0,1,2,3,4,5,6,7,8,9,10,11]:
----> 2 print(city_indices[index]+".", city_names[index])

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Sean P
  • 19
  • 1

1 Answers1

0

Answer to question:

fix to code in the question:

for index in [0,1,2,3,4,5,6,7,8,9,10,11]:
    print(f'{index}. {city_names[index]}')

using city_indices indexed from 0, not 1:

for index in city_indices:
    print(f'{index}. {city_names[index]}')

using zip:

city_indices = list(range(1, len(city_names)+1))

names_and_ranks = list()
for i, x in zip(city_indices, city_names):
    names_and_ranks.append(f'{i}. {x}')

with list comprehension:

names_and_ranks = [f'{i}. {x}' for i, x in zip(city_indices, city_names)]

Better way:

enumerate list:

names_and_ranks = [f'{i}. {x}' for i, x in enumerate(city_names, start=1)]

>>>
['1. Buenos Aires',
 '2. Toronto',
 '3. Pyeongchang',
 '4. Marakesh',
 '5. Albuquerque',
 '6. Los Cabos',
 '7. Greenville',
 '8. Archipelago Sea',
 '9. Walla Walla Valley',
 '10. Salina Island',
 '11. Solta',
 '12. Iguazu Falls']
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158