Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change multiple items in a list at one time in Python

Tags:

python

list

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.

like image 266
user17670 Avatar asked Apr 03 '15 02:04

user17670


People also ask

How do you replace multiple elements in a list in Python?

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.

Can you modify individual list elements Python?

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.

How do you replace a word in a list Python?

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 .


1 Answers

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]
like image 63
Avinash Raj Avatar answered Sep 28 '22 10:09

Avinash Raj