0

When the loop through ports runs, the variable afc_rem only gets set to all_fields on the first loop, then when values are removed, it never regains the full list of all_fields. Why does this happen?

if __name__ == "__main__":
 
    all_fields = ["byr","iyr","eyr","hgt","hcl","ecl","pid","cid"]
    
    ports = ["byr", "iyr"]
   
    for port in ports:
        afc_rem = all_fields
        for field in afc_rem:
            if field in port:
                afc_rem.remove(field)
                

L1ghtsp33D
  • 109
  • 1
  • 5
  • Here the working code. You should try. if __name__ == "__main__": all_fields = ["byr","iyr","eyr","hgt","hcl","ecl","pid","cid"] ports = ["byr","iyr"] out = list() for i in all_fields: if i not in ports: out.append(i) print(out) It iterates all_fields one by one. if ports is not found in all_fields, it appends to the new list. – shekhar chander Dec 12 '20 at 04:40

1 Answers1

-1

Explanation

Basically, when you assign afc_rem = all_fields then afc_rem is just a reference to in memory which means thats afc_rem still points to all_fields. You can observe this by doing inside loop:

print(id (afc_rem))
print( id ( all_fields))

Thus while removing items from afc_rem also removes items from all_fields.

Solution:

Try deep copy:

import copy
afc_rem = copy.deepcopy(all_fields)
Tarique
  • 1,273
  • 9
  • 15
  • The `list` contents are all immutable types; a deep copy isn't necessary. Shallow copying with `afc_rem = all_fields[:]` or `afc_rem = all_fields.copy()` is sufficient. – ShadowRanger Dec 12 '20 at 05:02
  • Yes. But if `afc_rem` becomes nested then shallow copy would not work. Would it??? Since the deep copy caters both the situation and there isn't a memory contrains it's better to use deep copy. – Tarique Dec 12 '20 at 05:50