-2

I have a list

Nodelist1 = [
    [['B', 10], ['IN', 1000]],
    [['C', 15], ['OUT', 1001]],
    [['F', 30], []]
]

I am checking if in list an element with index 1 is empty, If it is empty I want to remove it from the list.

My code is like this:

for i in range(len(Nodelist1)):
    if Nodelist1[i][1]==NULL:
        print "This node is deleted",Nodelist1[i][0]
        Nodelist1.remove(Nodelist1[i][0])
    else:
        print Nodelist1[i][0]

But this gives me an error:

Nodelist1.remove(Nodelist1[i][0])
ValueError: list.remove(x): x not in list.

Can some one help me here?

  • @Inbar: editing bounce, wheeee! :-) – Martijn Pieters Jul 16 '13 at 09:41
  • @MartijnPieters you kept forgetting the error formatting :) – Inbar Rose Jul 16 '13 at 09:42
  • What does `Nodelist1` contain? Clearly `Nodelist1[i][0]` is (no longer) in your list when you get that exception. It could be that it is already removed in a previous iteration. – Martijn Pieters Jul 16 '13 at 09:42
  • Is `Nodelist1 == Classlist1`? If not, what does `Nodelist1` look like? – filmor Jul 16 '13 at 09:43
  • @InbarRose: No, you kept destroying it. Tracebacks in Python have a certain pattern of indentation, source lines are indented further than the exception message itself. I won't keep editing it in, but the subtle difference there is bugging me. :-) – Martijn Pieters Jul 16 '13 at 09:43
  • Are you trying to remove the item(list) if it's empty? If you need to remove empty lists from a list then see the SO question : [How to remove empty lists from a list](http://stackoverflow.com/questions/4842956/python-how-to-remove-empty-lists-from-a-list) – Quicksilver Jul 16 '13 at 10:02

3 Answers3

3

It's not that clear to me what you are expecting the code to do - are you trying to remove [['F', 30], []] from your list 'ClassList'?

if you can do without the print statements, you can do this with a list comprehension:

result = [item for item in ClassList if item[1]]
Steve Allison
  • 1,091
  • 6
  • 6
1

I have a feeling that you are treating Python like C# (or something similar)

There is no NULL in Python. When you "delete" an item in a list, it is not replaced with an empty value, it is simply removed.

Example:

>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del l[5]
>>> l
[0, 1, 2, 3, 4, 6, 7, 8, 9]
>>> l.remove(4)
>>> l
[0, 1, 2, 3, 6, 7, 8, 9]

So, what you said:

I am checking if in list an element with index 1 is deleted, If it is deleted I want to remove it from the list.

Is not how Python works, once an item is deleted, it is already removed from the list, and you can not "check" that item. But you can check for the presence of the item:

>>> 4 in l
False
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
0

i think the way you remove an item in the nodelist is wrong

have you tried

Nodelist1.remove(i)
Francis Fuerte
  • 254
  • 1
  • 9