Check if item is in an array / list [duplicate]
Asked Answered
O

5

321

If I've got an array of strings, can I check to see if a string is in the array without doing a for loop? Specifically, I'm looking for a way to do it within an if statement, so something like this:

if [check that item is in array]:
Orella answered 28/6, 2012 at 19:39 Comment(2)
I think the question is already answered hereCarbonization
Or better here: #12934690Targett
S
599

Assuming you mean "list" where you say "array", you can do

if item in my_list:
    # whatever

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.

Sheepdog answered 28/6, 2012 at 19:40 Comment(4)
@jdi, and that loop will run much faster than the one coded explicitly in Python, not to mention being easier to read.Hoff
in is real nice, but I have to stress how nice using a lambda is for cases where we want to check if a substring is in a list of strings.Ruwenzori
@Ruwenzori I'd use a generator expression or a list comprehension for that, not a lambda.Sheepdog
And if you need to flip the condition it is if item not in my_list:Bulley
E
22

I'm also going to assume that you mean "list" when you say "array." Sven Marnach's solution is good. If you are going to be doing repeated checks on the list, then it might be worth converting it to a set or frozenset, which can be faster for each check. Assuming your list of strs is called subjects:

subject_set = frozenset(subjects)
if query in subject_set:
    # whatever
Ewart answered 28/6, 2012 at 19:43 Comment(0)
M
8

Use a lambda function.

Let's say you have an array:

nums = [0,1,5]

Check whether 5 is in nums in Python 3.X:

(len(list(filter (lambda x : x == 5, nums))) > 0)

Check whether 5 is in nums in Python 2.7:

(len(filter (lambda x : x == 5, nums)) > 0)

This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums.

For example, check whether any number that is greater than or equal to 5 exists in nums:

(len(filter (lambda x : x >= 5, nums)) > 0)
Meeks answered 11/9, 2017 at 16:33 Comment(1)
This works with Python2. With Python 3.7, you will get this error: TypeError: object of type 'filter' has no len()Hakodate
A
3

You have to use .values for arrays. for example say you have dataframe which has a column name ie, test['Name'], you can do

if name in test['Name'].values :
   print(name)

for a normal list you dont have to use .values

Alar answered 25/11, 2017 at 11:6 Comment(1)
I think you need a Pandas DataFrame object to use .values.Planospore
I
-5

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff
Isomerize answered 11/12, 2015 at 23:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.