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]:
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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
Method 3
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)
Method 4
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
Method 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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0