Get sublist from List based on indices in Python

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,

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.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top