python - Why does using "and" between two lists give me the second list (as opposed to an error)? -


this question has answer here:

i encountered bug in code. (incorrect) line similar to:

[x x in range(3, 6) , range(0, 10)]  print x  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

(the correct way of writing statement not part of question)

wondering somelist , someotherlist does, experimented. seems ever set result 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 , y       # [3, 4, 5, 6, 7, 8, 9] print y , x       # [0, 1, 2] print z , y , x # [0, 1, 2] 

i assume unintentional consequence of being able write is useful, i'm not seeing how semantics of "and" operator being applied here.

from experience, python won't apply operators things don't support operators (i.e. spits out typeerror), i'd expect error and-ing should never and-ed. fact don't error telling me i'm missing... something.

what missing? why list , list allowed operation? , there "useful" can done behaviour?

the and operator checks truthiness of first operand. if truthiness false, first argument returned, otherwise second.

so if both range(..)s contain elements, last operand returned. expression:

[x x in range(3, 6) , range(0, 10)] 

is equivalent to:

[x x in range(0, 10)] 

you can use if filter:

[x x in range(3, 6) if x in range(0, 10)]

in range(..) constructs list, making not terribly efficient. since know x int, can bounds check like:

[x x in range(3, 6) if 0 <= x < 10]

of course in case check useless since every element in range(3,6) in range of range(0,10).


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -