How to index two elements from a Python list?

Viewed 1937

How come I can't index a Python list for multiple out-of-sequence index positions?

mylist = ['apple','guitar','shirt']

It's easy enough to get one element, but not more than one.

mylist[0] returns 'apple', but mylist[0,2] returns TypeError: list indices must be integers or slices, not tuple

So far, only this seems to work which looks hectic:

np.asarray(mylist)[[0,2]].tolist()
4 Answers

Use list comprehension:

print([mylist[i] for i in [0, 2]])
# ['apple', 'shirt']

Or use numpy.array:

import numpy as np
print(np.array(mylist)[[0, 2]])
# ['apple', 'shirt']

Use Extended Slices:

mylist = ['apple','guitar','shirt']
print(mylist[::2])
#Output: ['apple', 'shirt']

Python list supports only integer and slice for indices. The standard slicing rule of python is as follow:

i:j:k inside the square bracket for accessing more than one element. where i is the starting index, j is the ending index and k is the steps.

>>> list_ =  ['apple','guitar','shirt']
>>> mylist[0:2]
['apple', 'guitar']

if you want some random element as per some certain indices then use List Comprehension or just a for loop

There is an another way for accessing items from certain indices by using map() function.

>>> a_list = [1, 2, 3]
>>> indices_to_access = [0, 2]

>>> accessed_mapping = map(a_list.__getitem__, indices_to_access)
>>> accessed_list = list(accessed_mapping)

>>> accessed_list
[ 1, 3]

A recommendation from me would be: use the NumPy library (import numpy as np). It will allow you to create a numpy array which has advantages over a standard list. Using the numpy array, you will be able to access as many items as you would like through a process called Fancy Indexing.

mylist[0] returns 'apple'

The above code/statement which was available in the question description depicts a Python programmer performing indexing- which is the process of passing the index position of a sinlge item in order to retrieve the item- However in the event of requiring multiple items, that would be difficult/not possible.

import numpy as np #import the numpy package

mylist = np.array(['apple','guitar','shirt']) #create the numpy array

mylist[[0,2]] #return the first and third items ONLY. (zero-indexed)
Out[11]: array(['apple', 'shirt'], dtype='<U6')

If you were to make use of the NumPy library in python (looking above), you would be able to create a NumPy array, which allows for more methods and operations to be performed on your array.

As compared to mylist[0] which returns a single/individual item only, Using mylist[[0,2]] we specify to the python compiler that we wish to retrieve exactly two elements from our list, and those elements are located at index positions '0' and '2'. (zero-indexed). Notice that we passed in the index positions of the desired elements in a list. Therefore instead of returning one element, we return two (or as many as you would like).

Related