Arturo A.
Arturo A.

Reputation: 1

python: Finding a index in one list and then replacing second list with the item from a index in first list

I am currently trying to find a item in a list, take it's position and find that same position in another list to replace it with the item in the first list.

example:

list_1 = ['a', 'b', 'c', 'a', 'b', 'c' ]

list_2 = ['1', '2', '3', '1', '2', '3']

I would try to find 'a', take it's index, find the index in the second list and replace that item in that index. So the ones become 'a' in list_2

Upvotes: 0

Views: 82

Answers (4)

Amir Khorasani
Amir Khorasani

Reputation: 170

You can find the index of any value with <sequence>.index(<value>).

This "index code" finds the desired item in the first list and in list_2 inserts this same item using the index just found:

list_1 = ['b', 'c', 'a', 'b', 'c' ]
list_2 = ['1', '2', '3', '1', '2', '3']

item = 'a'
item_index = list_1.index(item)
list_2.insert(item_index, item)

print(list_1)
print(list_2)

In the example above, the output is this:

['b', 'c', 'a', 'b', 'c']
['1', '2', 'a', '3', '1', '2', '3']

Upvotes: 0

PieCot
PieCot

Reputation: 3629

Something like this?

def replace_el(l1, l2, el):
    try:
        l2[l1.index(el)] = el
    except ValueError:
        pass

list_1 = ['a', 'b', 'c', 'a', 'b', 'c' ]
list_2 = ['1', '2', '3', '1', '2', '3']

replace_el(list_1, list_2, 'k')
print(list_2)
replace_el(list_1, list_2, 'a')
print(list_2)

And this is the output:

['1', '2', '3', '1', '2', '3']
['a', '2', '3', '1', '2', '3']

The function replace_el replaces the element of l2 in the same position of el in l1. If el is not in l1, l2 is unchanged.

Upvotes: 0

Alex S.
Alex S.

Reputation: 31

You could use list_1.index('a') to get 'a' index if there was only one instance of that letter. But as I might see you have duplicate values in your list so for loop should work for that.

list_1 = ['a', 'b', 'c', 'a', 'b', 'c' ]
list_2 = ['1', '2', '3', '1', '2', '3']
indexes = []
search_value = 'a'
for e, value in enumerate(list_1):  # e is basically our counter here so we use it later to find current position index
if value == search_value:
    indexes.append(e)
    
if len(indexes) > 0:  # check if our indexes list is not empty
    for index in indexes:
       list_2[index] = search_value
    
print(list_2)

Which will result in :

['a', '2', '3', 'a', '2', '3']

Upvotes: 0

SLDem
SLDem

Reputation: 2182

If I understand correctly the desired output would be this: ['a', '2', '3', '1', '2', '3']. So I would code it something like this:

list_1 = ['a', 'b', 'c', 'a', 'b', 'c']

list_2 = ['1', '2', '3', '1', '2', '3']


def replace_symbol(list_1, list_2, symbol):
    symbol_to_replace = list_1.index(symbol)
    list_2[symbol_to_replace] = symbol
    print(list_2)  # prints ['a', '2', '3', '1', '2', '3']
    return list_2


replace_symbol(list_1, list_2, 'a')  # pass the symbol to replace in the function call
        

Upvotes: 1

Related Questions