Can I change multiple items in a list at one time in Python?
Question1: For example,my list is
lst=[0,0,0,0,0]
I want to the third and fifth item become 99.I know I can do it by
lst[2] = 99
lst[4] = 99
However, is there any easier way to do this?
Question2:in the situation,my target value is[99,98], my index is [2,4],so my result would be [0,0,99,0,98]. Is there any easy way to do this? Thanks.
One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.
Update Item in a List. Lists in Python are mutable. All that means is that after defining a list, it is possible to update the individual items in a list.
If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
You could do like this,
>>> lst=[0,0,0,0,0]
>>> target = [99,98]
>>> pos = [2,4]
>>> for x,y in zip(pos,target):
lst[x] = y
>>> lst
[0, 0, 99, 0, 98]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With