As it was mentioned by @user202729 above, this code represents a practice that should be avoided, since it modifies a mutable object (the list l2
) in place inside a list comprehension and uses side effects of this modification. It is easy to make mistakes writing code like this and it may be difficult to spot these mistakes.
In any case, the goal is to create a list common
which consists of elements that are common to both l1
and l2
. Moreover, if some element appears n times in both lists, then it will be listed n times in common
.
The code uses the fact that Python evaluates logical expressions lazily.
In the conditon
if e in l2 and ((l2.pop(l2.index(e)) or True)
the first part e in l2
is evaluated first. If it gives False
i.e. the element e
of l1
is not in l2
, then the part after and
is not executed, e
is not included in common
, and the list comprehension moves on to the next element of l1
.
On the other hand, if e in l2
evaluates to True
, then the part after and
gets evaluated. The value of this part is always True
(due to the or True
bit), so e
becomes an element of common
. However, Python first runs l2.pop(l2.index(e))
which removes one occurrence of the element e
from the list l2
. For this reason, if the iteration encounters the same element e
in the list l1
again, then this element will be included in common
for the second time only if it appears in l2
also more than once.