📜  python set contains - Python (1)

📅  最后修改于: 2023-12-03 15:04:08.530000             🧑  作者: Mango

Python Set Contains

In Python, a set is an unordered collection of unique elements. It is similar to a list or tuple, but it does not allow duplicate values. You can check if an element is present in a set using the in operator, which returns True if the element is in the set, and False otherwise.

Example
fruits = {'apple', 'banana', 'orange'}
print('apple' in fruits) # True
print('pear' in fruits) # False
Performance

The in operator for sets operates in O(1) time on average, which means that it is very efficient even for large sets. This is because sets are implemented using hash tables, which allow for fast indexing and searching.

Conclusion

In summary, if you want to check if an element is present in a collection and you do not care about the order of the elements or duplicates, you should consider using a set. The in operator for sets provides a very efficient way to check if an element is in the set.