简体   繁体   中英

Python: Removing a single element from a nested list

I'm having trouble figuring out how to remove something from within a nested list.

For example, how would I remove 'x' from the below list?

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

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

TypeError: 'str' object doesn't support item deletion.

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

for char in lst:
    del char[0]

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

Perhaps you have defined lst as ['x',6,5,4] , in which case, you will indeed get the error you are mentioning.

Use the pop(i) function on the nested list. For example:

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

Done.

You can also use "pop". Eg,

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

will result in

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM