Python: removing a single item from a nested list

It’s hard for me to figure out how to remove something from a nested list.

For example, how to remove the "x" from the list below?

lst = [['x',6,5,4],[4,5,6]] 

I tried del lst[0][0] but got the following result:

TypeError: object 'str' does not support deleting an element.

I also tried the for loop, but got the same error:

 for char in lst: del char[0] 
+4
source share
3 answers

Your code is working fine. Are you sure lst is defined as [['x',6,5,4],[4,5,6]] ? Because if so, del lst[0][0] effectively removes 'x' .

You may have defined lst as ['x',6,5,4] , in which case you really get an error message.

+3
source

Use the pop(i) function in the nested list. For instance:

 lst = [['x',6,5,4],[4,5,6]] lst[0].pop(0) print lst #should print [[6, 5, 4], [4, 5, 6]] 

Done.

+2
source

You can also use "pop". For instance.

 list = [['x',6,5,4],[4,5,6]] list[0].pop(0) 

will result in

 list = [[6,5,4],[4,5,6]] 

See this topic for more: How to remove an item from a list by index in Python?

0
source

Source: https://habr.com/ru/post/1343559/


All Articles