0

Just the easy one which I could not find out why it works like that:

cities = ['Madrid', 'Barcelona', 'Valencia', 'Murcia']

for city in range(len(cities)):
    if cities[city] == 'Madrid':
        cities[city] = 1

    elif cities[city] == 'Barcelona':
        cities[city] = 2

    elif cities[city] == 'Valencia':
        cities[city] = 3

    else:
        cities[city] = 4

print(cities)

and this one gives [1, 2, 3, 4] as it should.

But if I do this:

cities = ['Madrid', 'Barcelona', 'Valencia', 'Murcia']
for city in cities:
    if city == 'Madrid':
        print('hey')
        city = 'Kiev'
print(cities)

Result is the following:

hey
['Madrid', 'Barcelona', 'Valencia', 'Murcia']

So, it recognizes 'Madrid', therefore prints hey, but then does not assign 'Kiev' to it. However in the first example, using index range, the reassignment is completed perfectly.

martineau
  • 119,623
  • 25
  • 170
  • 301
zum809
  • 23
  • 2

2 Answers2

1

Let's look at a similar piece of code:

cities = ['Madrid', 'Barcelona', 'Valencia', 'Murcia']
city = cities[0]
city = 'Kiev'
print(cities)

Output:

['Madrid', 'Barcelona', 'Valencia', 'Murcia']

Here, the final output doesn't have 'Kiev'. And we aren't surprised by this because nothing in the code modified the cities list. In your case, you have a for loop, but it is the same thing. There is no magic in the for loop that associates its variable to the original list. So changing the value of the city variable inside the for loop doesn't change the cities list.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

In each iteration city will be overriden by the next item in your list cities.

If you want that Madrid will be Kiev, than try this:

for i, city in enumerate(cities):
    if city == 'Madrid':
         cities[i] = "Kiev"
robni
  • 904
  • 2
  • 6
  • 20