[파이썬] 집합의 요소 포함 여부 연산

Python provides an efficient and convenient way to check whether an element is present in a set using the membership operator. The membership operator in allows us to determine if a given element exists in a set or not. In this blog post, we will explore how to perform element membership operations on sets in Python.

Creating a Set in Python

Before we dive into the membership operations, let’s first understand how to create a set in Python. A set is an unordered collection of unique elements. In Python, we can create a set using curly braces, enclosing comma-separated values or by using the set() function.

# Creating a set using curly braces
my_set = {1, 2, 3, 4, 5}

# Creating a set using the set() function
my_set = set([1, 2, 3, 4, 5])

Checking if an Element is Present in a Set

To check if an element is present in a set, we can use the membership operator in. The operator returns True if the element is found in the set, and False otherwise. Let’s see an example:

my_set = {1, 2, 3, 4, 5}

# Checking if an element is present using the membership operator
print(3 in my_set)  # Output: True
print(6 in my_set)  # Output: False

In the example above, we create a set my_set with elements from 1 to 5. Then, we use the membership operator in to check if 3 and 6 are present in the set. The output shows that 3 is present in the set, while 6 is not.

Using the not operator

We can also use the not operator along with the membership operator to check if an element is not present in a set. The not operator negates the result, returning True if the element is not found and False otherwise. Let’s see an example:

my_set = {1, 2, 3, 4, 5}

# Checking if an element is not present using the membership operator and the not operator
print(3 not in my_set)  # Output: False
print(6 not in my_set)  # Output: True

In the above example, we use the not operator along with the membership operator to check if 3 and 6 are not present in the set. The output shows that 3 is present in the set, so the result is False, while 6 is not present, so the result is True.

Conclusion

In this blog post, we explored how to perform element membership operations on sets in Python. We saw how to create a set using curly braces or the set() function and then checked if an element is present in the set using the membership operator in. We also learned how to use the not operator to check if an element is not present in the set.

Using these membership operations, you can easily determine if an element exists in a set, which can be helpful in various scenarios when dealing with sets in Python.