Removing Elements From A List Of A List
I have the data below, which is a list of lists. I would like to remove the last two elements from each list, leaving only the first three elements. I have tried list.append(), l
Solution 1:
You could use a list comprehension and create a new list of lists with 2 elements removed from each sublist
data = [x[:-2] for x in data]
Solution 2:
As @christian says, you have a list of tuple
, as opposed to list
. The distinction is significant here as tuple
is immutable. You can convert to list
of list
like this
data = map(list, data)
Now you can mutate each item as you iterate over it
foritemindata:
delitem[-2:]
In your case the list comprehension is better because it works on your list
of tuple
equally well.
Post a Comment for "Removing Elements From A List Of A List"