Home > Back-end >  How to put the same input character in a list but in different indexes according to the indexes wher
How to put the same input character in a list but in different indexes according to the indexes wher

Time:08-25

Let's say that I have the list ["x","x","x","x","x"]

And have the list ["p","a","s","t","a"]

And I want replace the "x"s in the first list that are the same indexes with both "a"s in the first list. So it will be like this ["x","a","x","x","a"]

How I can do that?

CodePudding user response:

You can loop list2 and replace elements in list1 based on a condition:

 for i,x in enumerate(list2): 
     list1[i]=x if x == 'a' else list1[i]

Or shoving that into list comprehension:

print([x if x=='a' else list1[i] for i,x in enumerate(list2)])

CodePudding user response:

Another possible solution would be by iterating the lists simultaneously:

>>> a = ["x","x","x","x","x"]
>>> b = ["p","a","s","t","a"]
>>> 
>>> a = [j if j == 'a' else i for i,j in zip(a,b)]
>>> a
['x', 'a', 'x', 'x', 'a']

Note: This solution assumes you want to replace items in the first list based on second list's items values e.g. 'a' in this case and not based on indexes

CodePudding user response:

First I have checked the length of the list_1 using len() function. Then using range() I got the index of each value in List_1. Now, in the for loop each time it will check the value in list_2 if it is 'a' then update the value in list_1 to 'a'.

list_1 = ["x","x","x","x","x"]
list_2 = ["p","a","s","t","a"]

for i in range(len(list_1)):
    if list_2[i] == 'a':
        list_1[i] = 'a'

print(list_1)

# using list comprehension
list_1 = [ 'a' if list_2[i] == 'a' else list_1[i] for i in range(len(list_1)) ]
print(list_1)

#Using enumarator()

list_1 = [ 'a' if j == 'a' else list_1[i] for i,j in enumerate(list_2)] print(list_1)

#output
['x', 'a', 'x', 'x', 'a']
  • Related