I would like to change the values of a list that is the value of a dictionary. When I code this in the pythonic way it does not work, but it does work when I use classical indexing of the list. To make clear what I mean I wrote a small demo. I want to increase all values lower than 4 in a list by one.
A = [1, 2, 3, 4, 5]
x = {"a": [1, 2, 3, 4, 5]}
print("example 1, this works")
A = [a+1 if a < 4 else a for a in A]
print(A)
print("example 2, this not")
for v in x.values():
v = [a + 1 if a < 4 else a for a in v]
print(x)
print("example 3, this not either")
for v in x.values():
for a in v:
a = a+1 if a < 4 else a
print(x)
print("example 4, but this does")
for v in x.values():
for i in range(len(v)):
if v[i] < 4: v[i] += 1
print(x)
Output:
example 1, this works
[2, 3, 4, 4, 5]
example 2, this not
{'a': [1, 2, 3, 4, 5]}
example 3, this not either
{'a': [1, 2, 3, 4, 5]}
example 4, but this does
{'a': [2, 3, 4, 4, 5]}
Two things are puzzling: 1. A list is treated differently depending on whether it is a dict value or not. 2. Changing a list value works or not depending on which looping technique you apply.
Is there a rationale that is beyond me? (Could be) If yes, what is it?