Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list as a list indices

Tags:

python

list

Suppose we have two lists

list_A = [1,3,4,54,3,5,6,2,6,77,73,39]
list_B = [0,3,2,8]

I want to access elements of list_A that have the values in list_B as their indices (without using loops).

After implementing it, the result should be as follows for the above case:

[1, 54, 4, 6]

Is there any easy method to do this without bothering with for loops (calling it explicitly in the code) ?

like image 354
maheshakya Avatar asked May 07 '26 08:05

maheshakya


1 Answers

Everything will use a loop internally*, but it doesn't have to be as complicated as you might think. You can try a list comprehension:

[list_A[i] for i in list_B]

Alternatively, you could use operator.itemgetter:

list(operator.itemgetter(*list_B)(list_A))

>>> import operator
>>> list_A = [1,3,4,54,3,5,6,2,6,77,73,39]
>>> list_B = [0,3,2,8]
>>> [list_A[i] for i in list_B]
[1, 54, 4, 6]
>>> list(operator.itemgetter(*list_B)(list_A))
[1, 54, 4, 6]

* OK! Maybe you don't need a loop with recursion, but I think it's definately overkill for something like this.

like image 147
arshajii Avatar answered May 09 '26 21:05

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!