0

When I do this:

i = [5, 6, 7, 5]

for el in i:

    el = 2

print(i)
# [5, 6, 7, 5]

the list is not updated (which is a trivial observation for someone who knows Python).

But when I do this:

i = [{'id': 5}, {'id': 6}, {'id': 7}, {'id': 5}]

for el in i:

    el['id'] = 2

print(i)
# [{'id': 2}, {'id': 2}, {'id': 2}, {'id': 2}]

then the list is updated.

Why is this exactly happening?

Even if a list of dicts is updated in this way, is this considered a bad technique to do something like that?

Outcast
  • 4,967
  • 5
  • 44
  • 99

2 Answers2

1

This is because python dict is mutable and not integer. this is why the list change. (https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/)

If you want to change you list you have to access the element by his index i.e l[i] = 2

Best regards

TOTO
  • 307
  • 1
  • 6
0

When you are running this code:

i = [5, 6, 7, 5]

for el in i:

    el = 2

you are just reassigning a variable inside of the loop without making any changes in the original list. To change the list you need to provide i[el] = 2 inside the loop.

But when you are running:

i = [{'id': 5}, {'id': 6}, {'id': 7}, {'id': 5}]

for el in i:

    el['id'] = 2

You are actually accessing the value in each dictionary in the list by the key and changing each value in the loop.

I suppose it's logically correct, so it's not a bad practice at all.

Please, correct me if i am wrong in comments - I am not a coder.

timanix
  • 94
  • 1
  • 3