how to remove an item in a list of list of string using index in python

Question:

input:

letters = [['a', 'b', 'c'], ['a', 'b', 'c']]
row= 0
column=0

output

[['b', 'c'], ['a', 'b', 'c']]

I tried to do this:

letters[0].remove(0)

but it gives me a value error, while when I use pop like this:

letters[0].pop(0) 

it does what I need but the problem with pop is that it returns me something while I just need the item to be removed

Asked By: Sarah Ahmadi

||

Answers:

letters = [['a', 'b', 'c'], ['a', 'b', 'c']]

del list1[0][0]

use the del keyword

Answered By: Caleb Bunch
  • list.remove() removes an item by value, not by index. So letters[0].remove('b') would work.
  • Simply deleting a single element with the same syntax, you could address it in any other statement is del which could be used as del letters[0][0]
  • As @Barmar said: list.pop) can return an element by index and remove it from the list.
Answered By: Niclas

You can try this if you want to delete the element by index value of the list:

del letters[0][0]  # [['b', 'c'], ['a', 'b', 'c']]
del letters[1][0]  # [['a', 'b', 'c'], ['b', 'c']]

or if you want remove specific value in the first occurance:

letters[0].remove('a')  # [['b', 'c'], ['a', 'b', 'c']]
letters[1].remove('a')  # [['a', 'b', 'c'], ['b', 'c']]
Answered By: A. N. C.
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.