0

The task: check if 'value' is in list_1 AND list_2

Approach below - is the result of 2 minutes intuitive playing

list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in (list_1 and list_2) # 'and' gets an intersection
print(r) #True

And it works in a way I expect. I've already seen solution like that - it works, but there is a little room of my misunderstanding, that's why I ask

(1) Can't find docs, describing how 'and' operator (should)works, for list, dicts, tuples etc.

(2) Why the following code returns 'False'

list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in (list_1, list_2) # Tuple?
print(r) #False

(3) Why it returns ['5', '7', '4']

list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in list_1 and list_2
print(r) # ['5', '7', '4']

(4) Why it returns (True, ['5', '7', '4'])

list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in list_1, list_2
print(r) # (True, ['5', '7', '4'])

I believe there is some doc at python docs web site, which enlightens questions above. It is possible to spend some time learning python 3 source code to see implementation details, but I am wondering of some language standart(like ECMAScript) which was used when Python 3 implementing

Community
  • 1
  • 1
  • You can use the intersection method of Python's set type for this task. As for what Python's `and` & `or` operators do, take a look at [this answer](http://stackoverflow.com/a/36551857/4014959). – PM 2Ring Sep 05 '16 at 13:10
  • @PM 2Ring, thank you for your comment - it is helpful + using a set solves that task too: '5' in set(p1.extend(p2)) – Aleksei Tatarnikov Sep 05 '16 at 17:45

1 Answers1

3

Your intuition about the first snippet is False. and returns the second of its operators if both are truthy, so here it returns the second list; so your statement is actually equivalent to '5' in list_2, which happens to be True.

The second is false because the tuple is actually now (['3', '5'], ['5', '7', '4']) - ie a tuple of two elements, both of which are lists. in will check if any members of the tuple are the string '5', but neither of them are.

The other two answers are just to do with operator precedence; the third is equivalent to ('5' in list_1) and list_2 which returns list_2 as explained above; and the third is equivalent to (('5' in list_1), list_2).

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895