0

I'm new to Python and in the process of rewriting an old Python script, I came across these lines:

value1 = 'some val 1'
value2 = 'some val 2'
some_list = #list of values

if (value1, value2) in some_list:

Does this check if value1 and value2 are in the list?

I googled how to do that and the answers show different approaches, and I didn't see any suggesting using the above code.

Is this doing something else? Should I keep it or change it?

1
  • 5
    No, this checks to see whether the tuple (value1, value2) is present in the list. Not the individual values themselves. Commented Apr 7, 2016 at 19:43

4 Answers 4

5

(value1, value2) is a tuple. Your check is seeing if that tuple is in the list. For example:

mylist = [4, 5, (4, 5), 6]
(4, 5) in mylist
>True #because the tuple (4, 5) is in the list
(5, 6)
>False #because although 5 and 6 are both in the list, the tuple is not.

If you want to see if every item in the tuple is in the list, use all() as mentioned by @apero:

mylist = [4, 5, 6, 7]
all(x in mylist for x in (4, 5, 6))
>True
all(x in mylist for x in (4, 5, 8))
>False
Sign up to request clarification or add additional context in comments.

Comments

3

You could use all:

>>> lst = [1, 2, 3, 4, 5]
>>> values = (1, 3)
>>> all(value in lst for value in values)
True
>>> values1 = (1, 6)
>>> all(value in lst for value in values1)
False

all evaluates to True only when all the values match the condition, in this case "being in the list". This is a really useful builtin method because it will stop evaluating as soon as 1 of the values does not match the condition. This technique is called short-circuit evaluation.

It behaves like if <test> and <test1> and <test2> .... : which evaluates each test one by one, from left to right and returns False as soon as one of the test doesn't pass.

Comments

1

Another one, using sets:

>>> to_find = {4, 5, 6}
>>> mylist = [4, 5, 6, 7]
>>> to_find.intersection(mylist) == to_find
True
>>> mylist = [5, 6, 7, 8]
>>> to_find.intersection(mylist) == to_find
False

Comments

0

if you want to check if any of the values are in the list:

>>> all(x in some_list for x in [value1, value2])

what you are doing now is checking if the tuple is in the list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.