Python: Removing a single element from a nested list
I'm having trouble figu开发者_开发知识库ring 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]
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.
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.
You can also use "pop". E.g.,
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?
精彩评论