Let me guess, you want to have a result like the following
[1, 2, 3, 'my_value', 'my_value']
To do this, you need to do this:
['my value' if i > 3 else i for i in x]
Update
Why your code doesn't work? Because i
is not a reference to an object but a primitive value assignment. Python variable reference assignment.
Update 2
If the element of the list is an object rather than a primitive, then it seems that i
become a reference to that object.
class A:
def __init__(self, val):
self.value = val
my_list = [A(1), A(2),A(3),A(4),A(5)]
for i in my_list:
if i.value > 3:
i.value = 'my_value'
print([i.value for i in my_list])
# [1, 2, 3, 'my_value', 'my_value']
Update 3
Please see some of the discussion in the comment below. In python, everything is an object. No primitive.
Ref: For Syntax