Ben
Ben

Reputation: 21625

How to modify the elements of one list based on another

I have two lists like

lst1 = ['a', 'b', 'c', 'd', 'e']
lst2 = ['q', 'r', 's']

Now, suppose I generate a mapping from list2 to list1 one like (4, 0, 3) meaning update the 4th element of list1 with the 0th element of list2, update the 0th element of list1 with the 1st element of list2, etc. such that the resulting list looks like

lst1 = ['r', 'b', 'c', 's', 'q']

How can I do this?

Upvotes: 0

Views: 46

Answers (1)

ASGM
ASGM

Reputation: 11381

One way would be to use enumerate:

lst1 = ['a', 'b', 'c', 'd', 'e']
lst2 = ['q', 'r', 's']
mapping = [4, 0, 3]

for lst2_n, lst1_n in enumerate(mapping):
    lst1[lst1_n] = lst2[lst2_n]

Upvotes: 2

Related Questions