4

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]
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Emily
  • 41
  • 1
  • 1
  • 2
  • Both work just fine for me, as I'd expect. Check if that's really your code. –  Mar 13 '11 at 21:36
  • It is funny that default syntax highlighter treats `char` as something special to Python as it is coloured blue. There is no built-in function called `char`, neither it's a keyword. – Maciej Ziarko Mar 13 '11 at 21:57
  • @Maciej: the syntax highlighter is not Python-specific. – Katriel Mar 13 '11 at 23:52
  • Yes, I know it. That's why I called it funny. The funniest thing - it treats `//` operator as a comment. The operator is going to be widely used in the future as Python3 has been released and it is becoming more and more popular. Stack Overflow should really work on it. More: http://meta.stackexchange.com/questions/81906/pythons-operator-treated-as-a-comment – Maciej Ziarko Mar 14 '11 at 00:21

3 Answers3

4

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.

JHSaunders
  • 599
  • 4
  • 12
  • `del lst[0][0]` works as well. And assuming JG is right (the only sensible explanatio I can think of), both will fail with OP's real code. –  Mar 13 '11 at 21:54
3

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.

João Silva
  • 89,303
  • 29
  • 152
  • 158
0

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?

Community
  • 1
  • 1
0x1mason
  • 757
  • 8
  • 20
  • Does it make a difference that the "x" I'm trying to remove is the symbol "["? It works when I use the above list, but not on my list. If I do lst[0][0] it does return '[' but it won't let me delete it. – Emily Mar 13 '11 at 21:51
  • Emily, really check if everything is correctly typed in your code. Strange things happen. – Maciej Ziarko Mar 13 '11 at 22:03
  • You're right, my list wasn't being created correctly. Thanks for your help :) – Emily Mar 13 '11 at 22:06