This tutorial will discuss about unique ways to get sublist from list based on indices in Python.
Table Of Contents
Method 1: Using List Comprehension
Iterate over list of index positions using a List comprehension, and for each index position, select the element at that index from the main list. So, the list comprehension will return sublist from list based on given indices.
Let’s see the complete example,
listOfNumbers = [12, 42, 78, 68, 91, 72, 71, 81, 82] # Index positions indices = [2, 5, 1] # Get a sublist containing elements from # original list at the given indices subList = [listOfNumbers[idx] for idx in indices] print (subList)
Output
[78, 72, 42]
Method 2: Using operator.itemgetter()
Decouple all indices in list, as individual elements (by applying astrik), and pass them to the “itemgetter()” function of operator module. It will return a callable object, containing multiple lookup values. Now pass your list object to it, and this will return values from the list at those index positions. Basically, it will return a sublist containing elements from list based on given indices.
Let’s see the complete example,
Frequently Asked:
- Get sublist from List based on indices in Python
- Python List count() method
- Add an element at the end of a List in Python
- Python : How to Check if an item exists in list ? | Search by Value or Condition
import operator listOfNumbers = [12, 42, 78, 68, 91, 72, 71, 81, 82] # Index positions indices = [2, 5, 1] # Get sublist based on given indices subList = operator.itemgetter(*indices)(listOfNumbers) print (subList)
Output
(78, 72, 42)
Summary
We learned about different ways to get a sublist from list based on index positions in Python. Thanks.