Reputation: 95
I want to modify list element using list comprehension.
z=[1,2,3]
z=[z[i]=1 for i in range(len(z))]
I want to get
z=[1,1,1]
but it doesn't work.
Upvotes: 0
Views: 2213
Reputation: 530922
If you want to modify z
in place, use a for
loop:
for i,_ in enumerate(z):
z[i] = 1
If you want to replace the list itself (not just change the existing list), use a list comprehension:
z = [1 for _ in z]
You can't use
z = [z[i]=1 for i in range(len(z))]
because the x
in [x for i in y]
must be an expression, and z[i] = 1
is not an expression; it's an assignment statement.
Upvotes: 0
Reputation: 13049
I want to modify list element using list comprehension.
z[:] = [1 for _ in z]
or:
[z.__setitem__(i, 1) for i in range(len(z))]
These will modify the existing list rather than create a new one. You can see this if you do print(id(z))
before and afterwards. Anything starting z =
will make z
point to a new list.
Upvotes: 0
Reputation: 178
if you want to change all the variables of a list into the same number, using list comprehension - you're basically creating a new list... so if that's your intention it should be like this:
z = [1,2,3]
z = [1 for x in z]
Output:
[1,1,1]
Upvotes: 1
Reputation: 669
Use this comprehension:
z = [z[0] for _ in z]
This will create a new list with the same length as the old list and will only contain the first element of the old list.
Upvotes: 0