Python array has element

Is there a short contains function for lists?

Given a list xs and a value item , how can I check whether xs contains item (i.e., if any of the elements of xs is equal to item )? Is there something like xs.contains(item) ? For performance considerations, see Fastest way to check if a value exists in a list.

Your question implies you’re only interested in list contains item, not list contains sublist? /tuple/ set/ frozenset/.

6 Answers 6

if my_item not in some_list: . 

It works fine for lists, tuples, sets and dicts (check keys).

Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.

With a list containing numpy arrays, will this check for numpy instances or values inside the numpy instances?

Beware ! This matches while this is very probably what you did not expect: o=’—skip’; o in («—skip-ias»); # returns True !

@AlexF: That matches because («—skip-ias») is not a tuple, but a string (the parentheses do nothing, just like (1) is just an integer). If you want a 1-tuple, you need to add a comma after the single item: («—skip-ias»,) (or (1,) ).

In addition to what other have said, you may also be interested to know that what in does is to call the list.__contains__ method, that you can define on any class you write and can get extremely handy to use python at his full extent.

>>> class ContainsEverything: def __init__(self): return None def __contains__(self, *elem, **k): return True >>> a = ContainsEverything() >>> 3 in a True >>> a in a True >>> False in a True >>> False not in a False >>> 

Источник

How to Check If Array Contains an Element in Python

Here are the ways to check if an array contains an element in Python:

Method 1: Using the “in” operator

To check if an array contains an element in Python, you can use the “in” operator. The in operator checks whether a specified element is an integral sequence element like an array, list, tuple, etc.

Читайте также:  Java collections get object

To create an array in Python, use the np.array() method.

Use the in operator to check if the array contains a “19” element.

import numpy as np arr = np.array([11, 19, 21]) element_exist = 19 in arr print(element_exist)

That means the array contains the “19” element, which is True because it is in the array.

Let me demonstrate an example where the array does not contain the provided element.

import numpy as np arr = np.array([11, 19, 21]) element_exist = 18 in arr print(element_exist)

Method 2: Using for loop

We will use a list as an array in this code.

cars = ['mercedez', 'bmw', 'ferrari', 'audi'] for car in cars: if car == 'bmw': print('It exists!')

Method 3: Using not in operator

cars = ['mercedez', 'bmw', 'ferrari', 'audi'] if 'bmw' not in cars: print('It exists!') else: print("Does not exist!")

Method 4: Using the lambda function

cars = ['mercedez', 'bmw', 'ferrari', 'audi'] element = list(filter(lambda x: 'mercedez' in x, cars)) print(element) 

That means an array contains an element in the list.

Method 5: Using any() function

cars = ['mercedez', 'bmw', 'ferrari', 'audi'] if any(element in 'audi' for element in cars): print('It exists')

Method 6: Using the count() method

cars = ['mercedez', 'bmw', 'ferrari', 'audi'] if cars.count('bmw') > 0: print("It exists!")

Источник

Python: Check if Array/List Contains Element/Value

In this tutorial, we’ll take a look at how to check if a list contains an element or value in Python. We’ll use a list of strings, containing a few animals:

animals = ['Dog', 'Cat', 'Bird', 'Fish'] 

Check if List Contains Element With for Loop

A simple and rudimentary method to check if a list contains an element is looping through it, and checking if the item we’re on matches the one we’re looking for. Let’s use a for loop for this:

for animal in animals: if animal == 'Bird': print('Chirp!') 

Check if List Contains Element With in Operator

Now, a more succinct approach would be to use the built-in in operator, but with the if statement instead of the for statement. When paired with if , it returns True if an element exists in a sequence or not. The syntax of the in operator looks like this:

Making use of this operator, we can shorten our previous code into a single statement:

if 'Bird' in animals: print('Chirp') 

This code fragment will output the following:

This approach has the same efficiency as the for loop, since the in operator, used like this, calls the list.__contains__ function, which inherently loops through the list — though, it’s much more readable.

Читайте также:  Битрикс модули include php

Check if List Contains Element With not in Operator

By contrast, we can use the not in operator, which is the logical opposite of the in operator. It returns True if the element is not present in a sequence.

Let’s rewrite the previous code example to utilize the not in operator:

if 'Bird' not in animals: print('Chirp') 

Running this code won’t produce anything, since the Bird is present in our list.

But if we try it out with a Wolf :

if 'Wolf' not in animals: print('Howl') 

Check if List Contains Element With Lambda

Another way you can check if an element is present is to filter out everything other than that element, just like sifting through sand and checking if there are any shells left in the end. The built-in filter() method accepts a lambda function and a list as its arguments. We can use a lambda function here to check for our ‘Bird’ string in the animals list.

Then, we wrap the results in a list() since the filter() method returns a filter object, not the results. If we pack the filter object in a list, it’ll contain the elements left after filtering:

retrieved_elements = list(filter(lambda x: 'Bird' in x, animals)) print(retrieved_elements) 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Now, this approach isn’t the most efficient. It’s fairly slower than the previous three approaches we’ve used. The filter() method itself is equivalent to the generator function:

(item for item in iterable if function(item)) 

The slowed down performance of this code, amongst other things, comes from the fact that we’re converting the results into a list in the end, as well as executing a function on the item on each iteration.

Check if List Contains Element Using any()

Another great built-in approach is to use the any() function, which is just a helper function that checks if there are any (at least 1) instances of an element in a list. It returns True or False based on the presence or lack thereof of an element:

if any(element in 'Bird' for element in animals): print('Chirp') 

Since this results in True , our print() statement is called:

This approach is also an efficient way to check for the presence of an element. It’s as efficient as the first three.

Check if List Contains Element Using count()

Finally, we can use the count() function to check if an element is present or not:

Читайте также:  String declaration in java class

This function returns the occurrence of the given element in a sequence. If it’s greater than 0, we can be assured a given item is in the list.

Let’s check the results of the count() function:

if animals.count('Bird') > 0: print("Chirp") 

The count() function inherently loops the list to check for the number of occurrences, and this code results in:

Conclusion

In this tutorial, we’ve gone over several ways to check if an element is present in a list or not. We’ve used the for loop, in and not in operators, as well as the filter() , any() and count() methods.

Источник

How to check if a list has a certain element in it

Say I don’t know what is in my_list , how can I check if «bye» is an element in my list. And if «bye» is an element in my_list , then how can I know which index it has (for this case «bye» is in my_list[1] )?

4 Answers 4

how can I check if «bye» is an element in my list.

then how can I know which index it is

You can skip the first step because if you try to find the index of a value that isn’t in the list, you will get a value error which you can handle like this:

try: my_list.index("not here") except ValueError: print("'not here' isn't in the list!!") 

And for a sufficiently long list, you should go to the try/except version, because otherwise you have to traverse the list twice and that’s slow 😛

try: idx = ['hi', 'bye', 'hi'].index('bye') except ValueError: print('Not in list.') else: print('In list at index', idx) 
try: i = my_list.index('hi') except ValueError: i = False 

i will hold the index if hi is in the list, otherwise it will be False, because list.index raises ValueErrror if it can’t return the index.

You can use the in operator to check if a specific item exists in a list. To find the index of any item in a list just use the .index() function. If you are a beginner in Python you can use the below method else you can check out exception handling.

my_list = ["hi", "bye", "hi"] if 'bye' in my_list: print "Word found at index %i",my_list.index('bye') else print 'Word not Found !' 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью