Slicing list of lists to get rid of the first item

Question:

How do I slice to get rid of "Hello", "World" and "Monty" in a list of lists? I have:

lst1 = [["Hello",1,2,3],["World",4,5,6],["Monty",7,8,9]]

I want:

lst2 = [[1,2,3],[4,5,6],[7,8,9]]
Asked By: Landon G

||

Answers:

You can reach it with a list comprehension and get in each iteration the last elements beside the first of the nested list by using the [1:] selector.

lst1 = [["Hello", 1,2,3], ["World",4,5,6],["Monty",7,8,9]]

lst2 = [item[1:] for item in lst1]
print (lst2)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Answered By: omri_saadon

You can get a slice of a list lst starting with the second element using lst[1:]. To do it for each sublist you can use a list comprehension:

>>> lst1 = [["Hello", 1, 2, 3], ["World", 4, 5, 6], ["Monty", 7, 8, 9]]
>>> lst2 = [lst[1:] for lst in lst1]
>>> lst2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Answered By: Eugene Yarmash
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.