pythonlistnested

TypeError: list indices must be integers, not tupl


This is a common question on SO but all the examples I've looked at are fairly complicated. So I am posting the simplest example I can think of to get a straight-forward answer.

x = [(1,2),(3,4),(5,6)]
print(x[0])
  (1,2)
print(x[0,1])
  TypeError: list indices must be integers or slices, not tuple

The error message indicates that if I want a consecutive range of elements, I can use a slice: x[0:2]. But what if I want non-consecutive elements like x[0,2]? How do I get those by index?


Solution

  • Using pure python you could use a list comprehension

    def get_values(data, indices):
      return [data[i] for i in indices]
    

    For example

    >>> x = [(1,2),(3,4),(5,6)]
    >>> get_values(x, [0, 2])
    [(1, 2), (5, 6)]
    

    Using numpy you could directly use another array to index

    >>> import numpy as np
    >>> arr = np.array([(1,2),(3,4),(5,6)])
    >>> arr[np.array([0,2])]
    array([[1, 2],
           [5, 6]])