What are the methods to replace one value of list with value of another list in Python?

python

#1

Hi,

I have two lists and now I want to replace value of one list with value of another list of same index number.

Here I have one list for Adv_Code and another one for SM_Code. Now, I want to replace value of Adv_Code with SM_Code if Adv_Code equals to 1015.

Adv_Code = [1010, 1011, 1012, 1013, 1014, 1015, 1011, 1015]  
SM_Code= [22, 23, 24, 25, 26, 27, 28, 29]

I’m new to python, please help me to perform this. Many thanks.

Steve


#2

@Steve

Below is solution, I have done it using loop to access list values and update it. You can also perform it using other methods like list comprehension and others.

Create List for Adv_Code and SM_Code

Adv_Code = [1010, 1011, 1012, 1013, 1014, 1015, 1011, 1015]  
SM_Code= [22, 23, 24, 25, 26, 27, 28, 29]

Code
In [28]:

i=0
for num in Adv_Code:
    if num==1015:
        Adv_Code[i]=SM_Code[i]
    i=i+1
print Adv_Code

Output
[1010, 1011, 1012, 1013, 1014, 27, 1011, 29]

Regards,
Sunil