Skip to content

Python select list elements by index

  • by

Use listName[index] syntax to select list elements by index in Python. Just use a list name with square barkiest and pass index value.

list[index_value]

Python selects list elements by index examples

A simple example code selects an item from a list by knowing its position in the list.

listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
res = listA[0]

print("Selected list elements by index:", res)

Output:

Python select list elements by index

Find elements of a list by indices in Python

Use the getitem() method along with the map function to access the list of items.

listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
listB = [0, 1, 3]

res = list(map(listA.__getitem__, listB))

print(res)

Output: [‘Mon’, ‘Tue’, ‘Thu’]

The operator module provides itemgetter() method which can be used for this purpose.

res=list((itemgetter(*listB)(listA)))

With numpy

res=list(np.array(listA)[listB])

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading