Can I change multiple items in a list at one time in Python?
Question1: For example,my list is
JavaScript
x
2
1
lst=[0,0,0,0,0]
2
I want to the third and fifth item become 99.I know I can do it by
JavaScript
1
3
1
lst[2] = 99
2
lst[4] = 99
3
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.
Advertisement
Answer
You could do like this,
JavaScript
1
10
10
1
>>> lst=[0,0,0,0,0]
2
>>> target = [99,98]
3
>>> pos = [2,4]
4
>>> for x,y in zip(pos,target):
5
lst[x] = y
6
7
8
>>> lst
9
[0, 0, 99, 0, 98]
10