I encountered a bug in some code. The (incorrect) line was similar to:
[x for x in range(3, 6) and range(0, 10)]
print x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
(the correct way of writing this statement is not part of the question)
Wondering what someList and someOtherList
does, I experimented. It seems to only ever set the result to the last parameter passed:
x = range(0,3) # [0, 1, 2]
y = range(3, 10) # [3, 4, 5, 6, 7, 8, 9]
z = range(4, 8) # [4, 5, 6, 7]
print x and y # [3, 4, 5, 6, 7, 8, 9]
print y and x # [0, 1, 2]
print z and y and x # [0, 1, 2]
I would assume that this is an unintentional consequence of being able to write something that is useful, but I'm not really seeing how the semantics of the "and" operator are being applied here.
From experience, python won't apply operators to things that don't support those operators (i.e. it spits out a TypeError), so I'd expect an error for and-ing something that should never be and-ed. The fact I don't get an error is telling me that I'm missing... something.
What am I missing? Why is list and list
an allowed operation? And is there anything "useful" that can be done with this behaviour?