0

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]
1
  • After [x.pop(1) for x in li] li will have your desired output. You just need to print it print li. Commented Apr 21, 2016 at 6:41

3 Answers 3

2

You can use the del operator like this:

for sublist in list:
    del sublist[1]
Sign up to request clarification or add additional context in comments.

Comments

1

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)   

Comments

0

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 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.