Reputation: 137
Here i want remove items in list of list by index. Input is
li = [[1,2,3,4],[5,6,7,8]]
Excepted output is
[[1,3,4],[5,7,8]]
What I'm tried is,
print [x.pop(1) for x in li]
Upvotes: 0
Views: 3066
Reputation: 52133
You actually removed the items in the given index but you printed out the wrong list. Just print li
after you pop the items:
>>> [x.pop(1) for x in li]
>>> print li
However, do you really have to use list comprehensions? Because calling .pop()
in a list comprehension will accumulate the removed items and creates a new, totally useless list with them.
Instead, you can just do the following:
>>> for lst in li:
... lst.pop(1)
Upvotes: 1
Reputation: 148890
pop
, like del
change the underlying list so you must explicitely loop through the sublists to remove second element and them print the modified list.
for l in li: del l[1]
print li
If on the other hand, you do not want to change the lists but directly print the result, you could use a list comprehension:
print [ (l[:1] + l[2:]) for l in li ]
Upvotes: 0
Reputation:
You can use the del
operator like this:
for sublist in list:
del sublist[1]
Upvotes: 2