Horse SMith
Horse SMith

Reputation: 1035

Slice away first element in each (list) element in a list in Python

Say we have a list:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Then I want to create a new list through slicing away the first element in each element in the list:

b = a[][1:]

Obviously the above doesn't work, but what I want b to be now is:

[[2, 3], [5, 6], [8, 9]]

Of course I can just loop through it, but all I want to know is if it's possible to do it in any similar way of what I tried so wrongly to do above. Also, preferably is there a better/good way of doing this with numpy, in which case it doesn't need to be done through slicing the way I attempted to do it?

Upvotes: 1

Views: 1389

Answers (3)

yemu
yemu

Reputation: 28309

in python 3 you can also use *

b = [x for _,*x in a]

this approach is more flexible since you can for example left first and last elements of the inside list, no matter how long is the list:

b = [first,last for first,*middle,last in a]

Upvotes: 2

bcollins
bcollins

Reputation: 3459

Using numpy indexing/slicing notation, you use commas to delimit the slice for each dimension:

import numpy as np
a = np.array([[1,2,3],[1,2,3],[1,2,3]])
print a[:,1:]

output:

[[2 3]
 [2 3]
 [2 3]]

For additional reading on numpy indexing: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

Upvotes: 5

karthikr
karthikr

Reputation: 99680

You can use list comprehensions:

b = [x[1:] for x in a]

Demo:

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b = [x[1:] for x in a]
>>> b
[[2, 3], [5, 6], [8, 9]]
>>>

Upvotes: 6

Related Questions