Menu Close

How to access multiple elements of list knowing their index with Python?

Sometimes, we want to access multiple elements of list knowing their index with Python.

In this article, we’ll look at how to access multiple elements of list knowing their index with Python.

How to access multiple elements of list knowing their index with Python?

To access multiple elements of list knowing their index with Python, we can use the itemgetter function.

For instance, we write

from operator import itemgetter 

a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))

to call itemgetter with the indexes of b as the arguments.

And then we call the returned function with a to return a tuple of the items in a with the indexes in b.

Conclusion

To access multiple elements of list knowing their index with Python, we can use the itemgetter function.

Posted in Python, Python Answers