slicing list of lists in Python

40,980

Solution 1

With numpy it is very simple - you could just perform the slice:

In [1]: import numpy as np

In [2]: A = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])

In [3]: A[:,:3]
Out[3]: 
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

You could, of course, transform numpy.array back to the list:

In [4]: A[:,:3].tolist()
Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Solution 2

Very rarely using slice objects is easier to read than employing a list comprehension, and this is not one of those cases.

>>> A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
>>> [sublist[:3] for sublist in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

This is very clear. For every sublist in A, give me the list of the first three elements.

Solution 3

A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

print [a[:3] for a in A]

Using list comprehension

Solution 4

you can use a list comprehension such as: [x[0:i] for x in A] where i is 1,2,3 etc based on how many elements you need.

Share:
40,980
HuckleberryFinn
Author by

HuckleberryFinn

I work with Tensorflow (mostly) and PyTorch.

Updated on July 09, 2022

Comments

  • HuckleberryFinn
    HuckleberryFinn almost 2 years

    I need to slice a list of lists in python.

    A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
    idx = slice(0,4)
    B = A[:][idx]
    

    The code above isn't giving me the right output.

    What I want is : [[1,2,3],[1,2,3],[1,2,3]]

  • Wayne Werner
    Wayne Werner about 8 years
    While that does solve the OPs problem, I doubt it was what they were going for.
  • Sid
    Sid about 8 years
    Why? he needs the first idx elements from each list.
  • Sid
    Sid about 8 years
    @WayneWerner correct but I changed the meaning of idx...instead of the slice it's a raw int
  • Wayne Werner
    Wayne Werner about 8 years
    the OP is defining idx = slice(0,4), not 4.
  • Sid
    Sid about 8 years
    fixed to change the name of idx to i
  • greybeard
    greybeard almost 5 years
    Welcome to StackOverflow! While this prints what HuckleberryFinn wrote he wanted, he wanted it without mentioning the indices of A, using a slice object for the 2nd dimension. There's an error in your third argument to print().