1

Similar to Removing dicts with duplicate value from list of dicts, but seeking understanding not just an answer.

I am confronted with a result that exposes a fundamental gap in my understanding of lists, loops, or the list.remove() function. Perhaps an explanation would be helpful to others facing the same question:

>>> my_dict_list = [
    {'a': 50, 'b': 4000},
    {'a': 4000, 'b': 4000},
    {'a': 5000, 'b': 5000},
    {'a': 501, 'b': 501},
    {'a': 400, 'b': 100},
    {'a': 4000, 'b': 4000},
    {'a': 5000, 'b': 5000},
]

Resulting confusion using a simple loop to remove dicts where 'a' and 'b' values are equal:

>>> for d in my_dict_list:
...     if d['a'] == d['b']:
...         my_dict_list.remove(d)
...         
>>> my_dict_list
[{'a': 50, 'b': 4000}, {'a': 5000, 'b': 5000}, {'a': 400, 'b': 100}, {'a': 5000, 'b': 5000}]

Not understanding the above is leaving a gaping wound in my soul. Some were removed, others were not.

BTW: this easily gets the correct result:

>>> [d for d in my_dict_list if d['a'] != d['b']]
[{'a': 50, 'b': 4000}, {'a': 400, 'b': 100}]
martineau
  • 119,623
  • 25
  • 170
  • 301
neil.millikin
  • 1,077
  • 1
  • 10
  • 15
  • 2
    Modifying an iterable as you iterate over it will usually result in bugs. Don't do it! The second form you did is the preferred way. – Samwise Dec 21 '20 at 19:40
  • https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/ – Samwise Dec 21 '20 at 19:43
  • also here: https://stackoverflow.com/questions/50127618/modifying-a-list-while-iterating-over-it-with-python – neil.millikin Dec 21 '20 at 19:45

0 Answers0