Python: Removing a single element from a nested list

Emily picture Emily · Mar 13, 2011 · Viewed 8.6k times · Source

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]

Answer

João Silva picture João Silva · Mar 13, 2011

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.