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]
4
  • Both work just fine for me, as I'd expect. Check if that's really your code. Commented Mar 13, 2011 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. Commented Mar 13, 2011 at 21:57
  • @Maciej: the syntax highlighter is not Python-specific. Commented Mar 13, 2011 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: meta.stackexchange.com/questions/81906/… Commented Mar 14, 2011 at 0:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

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?

3 Comments

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, really check if everything is correctly typed in your code. Strange things happen.
You're right, my list wasn't being created correctly. Thanks for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.