Indexing of python 2D list

13,440

An array and nested list version:

In [163]: A=np.arange(12).reshape(3,4)
In [164]: Al = A.tolist()

For sliced indexing, a list comprehension (or mapping equivalent) works fine:

In [165]: A[:,1:3]
Out[165]: 
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])
In [166]: [l[1:3] for l in Al]
Out[166]: [[1, 2], [5, 6], [9, 10]]

For advanced indexing, the list requires a further level of iteration:

In [167]: A[:,[0,2,3]]
Out[167]: 
array([[ 0,  2,  3],
       [ 4,  6,  7],
       [ 8, 10, 11]])

In [169]: [[l[i] for i in [0,2,3]] for l in Al]
Out[169]: [[0, 2, 3], [4, 6, 7], [8, 10, 11]]

Again there are various mapping alternatives.

In [171]: [operator.itemgetter(0,2,3)(l) for l in Al]
Out[171]: [(0, 2, 3), (4, 6, 7), (8, 10, 11)]

itemgetter uses tuple(obj[i] for i in items) to generate those tuples.

Curiously, itemgetter returns tuples for the list index, and lists for slices:

In [176]: [operator.itemgetter(slice(1,3))(l) for l in Al]
Out[176]: [[1, 2], [5, 6], [9, 10]]
Share:
13,440
Kevin
Author by

Kevin

Updated on June 04, 2022

Comments

  • Kevin
    Kevin almost 2 years

    In order to access the second dimension of a 2D numpy array, we could use e.g.

    A[:,0:9]
    

    How could we do this to a 2D list?

  • juanpa.arrivillaga
    juanpa.arrivillaga about 7 years
    It seems over-engineered to me. Just a simple [sub[0:9] for sub in A] works nicely: it is efficient and readable.
  • Paul Panzer
    Paul Panzer about 7 years
    @juanpa.arrivillaga fair enough.
  • juanpa.arrivillaga
    juanpa.arrivillaga about 7 years
    In the end, I'm not sure efficiency matters here... if OP want's efficient multidimensional slicing, they should use numpy!
  • Paul Panzer
    Paul Panzer about 7 years
    @juanpa.arrivillaga I wouldn't at all be surprised if your solution is faster.
  • hpaulj
    hpaulj about 7 years
    Slices work with lists ok, it's list indexing that needs extra help, such as the itemgetter, which is just a class wrapper for a list comprehension.
  • Paul Panzer
    Paul Panzer about 7 years
    @hpaulj Sorry, I don't follow. What is your point? I'm only using itemgetter in order to be able to apply map.
  • hpaulj
    hpaulj about 7 years
    It's more of an observation about itemgetter. It may be useful, but it doesn't add a compiled array-like access to lists.
  • Paul Panzer
    Paul Panzer about 7 years
    @hpaulj Ok. Yeah, I think I'm just delaying the inevitable: Having to admit that the plain list comprehension is indeed the best solution here -- short of switching to numpy that is.