0

I'm trying to del an object in my list inside my loop but it's not working.

data = []

data.append({
    'one': 1,
    'two': 2
})

data.append({
    'one': 3,
    'two': 4
})

data.append({
    'one': 5,
    'two': 6
})

for d in data:
    if d['one'] == 3:
        del d

It's impossible to delete my object like that ? del d

The only one solution that I found is to create a counter then delete with index in the data list del data[x]

John
  • 4,711
  • 9
  • 51
  • 101

3 Answers3

2

del d unbinds the name d, which is just another reference to one of the dictionaries in data. Since references are reassigned and unbound independently (see this classic) you won't see any changes to data.

In general, it is error prone to remove items from a list while iterating over it.

The conventional wisdom aquired from hundreds of years of programming Python says to build a new list and rebind the name.

>>> data = [d for d in data if d['one'] != 3]
>>> data
[{'two': 2, 'one': 1}, {'two': 6, 'one': 5}]
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You can use filter:

data = filter(lambda x: x['one'] != 3, data)
Vanojx1
  • 5,574
  • 2
  • 23
  • 37
1

You cannot delete items from a list while you are iterating through it because the list indices change as you delete elements. Also del d simply deleted the name d, the dictionary will still exist in the list.

The best solution here is to create a new list with the unwanted elements filtered out:

data = [d for d in data if d['one'] != 3]

If it is important to modify the existing list data because there are other references to it that must also see the changes you can use a slice assignment to update the original list, but this is not usually needed:

data[:] = [d for d in data if d['one'] != 3]
Duncan
  • 92,073
  • 11
  • 122
  • 156