Skip to content
Advertisement

Change multiple items in a list at one time in Python

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.

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement