Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *