[파이썬] 집합의 정의와 생성

집합은 고유한 값들의 모임을 나타내는 자료 구조입니다. 집합은 원소의 순서를 관리하지 않으며, 중복된 값을 허용하지 않습니다.

파이썬에서 집합을 생성하고 다양한 연산을 수행하는 방법에 대해 알아보겠습니다.

집합 생성하기

파이썬에서 빈 집합을 생성하려면 set() 함수를 사용하거나 중괄호 {}를 사용할 수 있습니다. 중괄호를 사용한 집합 생성은 사전(dictionary)의 생성과 혼동될 수 있으므로 주의해야 합니다.

empty_set = set()
print(empty_set)  # 출력: set()

fruits = {'apple', 'banana', 'orange'}
print(fruits)  # 출력: {'apple', 'banana', 'orange'}

집합 연산하기

파이썬은 다양한 집합 연산을 지원합니다.

원소 추가하기

집합에 원소를 추가할 때는 add() 메서드를 사용합니다.

fruits = {'apple', 'banana', 'orange'}
fruits.add('strawberry')
print(fruits)  # 출력: {'apple', 'banana', 'strawberry', 'orange'}

원소 제거하기

집합에서 원소를 제거할 때는 remove() 메서드를 사용합니다. 제거하려는 원소가 없는 경우 KeyError가 발생하므로 discard() 메서드를 사용하면 원소가 없어도 오류가 발생하지 않습니다.

fruits.remove('banana')
print(fruits)  # 출력: {'apple', 'strawberry', 'orange'}

fruits.discard('kiwi')
print(fruits)  # 출력: {'apple', 'strawberry', 'orange'}

집합 연산하기

파이썬의 집합은 수학의 집합과 유사한 연산을 지원합니다. 예를 들어, 합집합, 교집합, 차집합 등의 연산을 쉽게 수행할 수 있습니다.

fruits = {'apple', 'banana', 'orange'}
vegetables = {'carrot', 'broccoli', 'tomato'}

# 합집합
combined_set = fruits.union(vegetables)
print(combined_set)  # 출력: {'banana', 'broccoli', 'tomato', 'carrot', 'orange', 'apple'}

# 교집합
intersection_set = fruits.intersection(vegetables)
print(intersection_set)  # 출력: set()

# 차집합
difference_set = fruits.difference(vegetables)
print(difference_set)  # 출력: {'banana', 'orange', 'apple'}

요약

파이썬의 집합은 고유한 값들의 모임을 나타내는 자료 구조입니다. 집합은 중복된 값을 허용하지 않으며, 원소의 순서도 관리하지 않습니다. 집합을 생성하고 다양한 연산을 수행하는 방법을 배웠습니다. 이러한 집합 연산을 적절히 활용하면 파이썬 프로그래밍에서 유용하게 활용할 수 있습니다.