Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if something is (not) in a list in Python

I have a list of tuples in Python, and I have a conditional where I want to take the branch ONLY if the tuple is not in the list (if it is in the list, then I don't want to take the if branch)

if curr_x -1 > 0 and (curr_x-1 , curr_y) not in myList:       # Do Something 

This is not really working for me though. What have I done wrong?

like image 425
Zack Avatar asked May 02 '12 00:05

Zack


People also ask

How do you check if an item is not in a list in Python?

“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.

How do you check if an object is in a list in Python?

Use the any() function to check if an object exists in a list of objects. The any() function will return True if the object exists in the list, otherwise False is returned.

How do you check if a value is in a list?

Besides the Find and Replace function, you can use a formula to check if a value is in a list. Select a blank cell, here is C2, and type this formula =IF(ISNUMBER(MATCH(B2,A:A,0)),1,0) into it, and press Enter key to get the result, and if it displays 1, indicates the value is in the list, and if 0, that is not exist.

How do you check if something is not in a string Python?

The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .


1 Answers

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4] False >>> 3 not in [4, 5, 6] True 

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)] False >>> (2, 3) not in [(2, 7), (7, 3), "hi"] True 
like image 168
orlp Avatar answered Sep 19 '22 13:09

orlp