1

I am wondering if I can replace values of a list with elements of another list based on the index in Python:

let's say

a=[3, 2, 8, 7, 0]
d=['a','b','c','d','e','f','g','h','i']

I want to replace the elements of list a with the elements of list d. Values of list a define the index number of list d.

I want a list like c,

c=['d','c','i','a']
3
  • Better to think in terms of making a new list than replacing. Commented Sep 27, 2021 at 7:30
  • Please provide enough code so others can better understand or reproduce the problem. Commented Oct 5, 2021 at 9:18
  • So, there is a calculation for a single element, from a, which consists of using that element as an index into d. Clearly we know how to write that: by indexing with []. The next trick is to repeat that calculation for the elements of a, and collect them into c. Please see the linked duplicate for this technique. Commented Sep 29, 2023 at 3:32

4 Answers 4

4
a = [3,2,8,7,0]
b = ['a','b','c','d','e','f','g','h','i']
l = [b[i] for i in a]
# d, c, i, a
Sign up to request clarification or add additional context in comments.

Comments

0

I would do it in this manner: (anyway I am curious if there is another, simplest way)

c=[]
a=[3, 2, 8, 7, 0]
d=['a','b','c','d','e','f','g','h','i']
for index in a:
    c.append(d[index])

print(c)

result: c = ['d', 'c', 'i', 'h', 'a']

Comments

0
a=[3, 2, 8, 7, 0]
d=['a','b','c','d','e','f','g','h','i']
d = np.array(d)
d[[a]]

This can be done with the help of numpy.

Comments

0

Use __getitem__ with map which is quite faster.

list(map(d.__getitem__, a))
Output >> ['d', 'c', 'i', 'h', 'a']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.