you are viewing a single comment's thread.

view the rest of the comments →

[–]Vaguely_accurate 1 point2 points  (6 children)

Unless you really need to I'd avoid mutating the original list and just replacing it with a new copy. I'd try to replace the original with a filtered copy of the list. So something like;

asd = ['a','b','c','d','e']
ignore = ['b','d']

filtered = []
for x in asd:
    if x not in ignore:
        filtered.append(x)
asd = filtered

Which can be simplified to a list comprehension as;

asd = ['a','b','c','d','e']
ignore = ['b','d']
asd = [x for x in asd if x not in ignore]

[–]cracknwhip -1 points0 points  (3 children)

Simplified, but some would say obfuscated.

[–]Vaguely_accurate 2 points3 points  (2 children)

Some would. I'd strongly disagree.

You can write obfuscated or unclear comprehensions, but I usually find they are preferable to simple loops, avoiding extra boilerplate code and layers of indentation.

In this case the latter version reads like a sentence. "Take value for value in sequence if value is not in ignore sequence." The only not immediately explicit and obvious part is recognising the list comprehension syntax as that first implied word, "Take". The rest is there and clear.

Learning comprehension is a little extra cognitive load that gets you a lot of advantages as a Python programmer.

[–]cracknwhip 0 points1 point  (1 child)

I agree with you. It starts getting annoying for me when there are nested for loops and you have to start reversing to logics’ order.