Why this code is not going to the second "if part" but when I comment out the remove statements then it is going to the second "if part" i need to take out 'abc' and 'abcd' and 'defg' from d['a'] below is my code.
d={'a': ['abc','def','ghi','abcd','ghij'], 'b': [6, 7, 8]}
for i in d['a']:
if i.startswith("a"):
d['a'].remove(i)
#print('1st print '+i)
if i.startswith("d"):
d['a'].remove(i)
#print('2nd print '+i)
print(d)
It is not a good practice to remove element from a list while iterating over it. In your case you can use a simple list comprehension.
Ex:
d={'a': ['abc','def','ghi','abcd','ghij'], 'b': [6, 7, 8]}
d["a"] = [i for i in d["a"] if not i.startswith(("a", "d"))]
print(d)
Output:
{'a': ['ghi', 'ghij'], 'b': [6, 7, 8]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With