0

I was doing exercise from a book, and I wrote this code somehow, which was about making a list of dicts that contains some information, looping through each dict and modifying their value

aliens = []
for i in range(5):
    new_alien = {"color": "green", "points": 5, "speed": "slow"}
    aliens.append(new_alien)

print(aliens)

print("#" * 30)

for i in aliens:
    i["color"] = "yellow"
    i["speed"] = "medium"
    i["points"] = 10

print(aliens)
print(len(aliens))

I'm getting the same result as if the code on the second part was

for i in range(len(aliens)):
    aliens[i]["color"] = "yellow"
    aliens[i]["speed"] = "medium"
    aliens[i]["points"] = 10

And the second for loop was modifying values in dicts somehow. To my understanding, variables like "i" from the second loop, only act as a temp variable that holds values, manipulating them only affects what it hold, like

# unrelated code
ls = list(range(11, 21))

for i in ls:
    i = 2

print(ls)

Why was this happening, did I wrote something wrong? Is this like a feature? Or did I misunderstood something?

FULL CODE:

aliens = []
for i in range(5):
    new_alien = {"color": "green", "points": 5, "speed": "slow"}
    aliens.append(new_alien)

print(aliens)

print("#" * 30)

for i in aliens:
    i["color"] = "yellow"
    i["speed"] = "medium"
    i["points"] = 10


# for i in range(len(aliens)):
#     aliens[i]["color"] = "yellow"
#     aliens[i]["speed"] = "medium"
#     aliens[i]["points"] = 10

print(aliens)
print(len(aliens))

vid Proli
  • 27
  • 4

0 Answers0