집합 생성 및 요소 추가
첫 번째 단계에서는 집합을 생성하고 새 요소를 추가하는 방법을 배웁니다. 집합은 고유한 항목들의 컬렉션이므로, 중복된 요소는 자동으로 제거됩니다.
여러분의 환경에는 set_basics.py라는 빈 파일이 포함되어 있습니다. 편집기 왼쪽의 파일 탐색기를 사용하여 ~/project/set_basics.py를 찾아 엽니다.
다음 Python 코드를 파일에 추가합니다. 이 코드는 집합을 생성하는 몇 가지 방법을 보여줍니다.
## Method 1: Using curly braces {}
## This creates a set with initial elements.
my_set = {'apple', 'banana', 'cherry'}
print("Set created with braces:", my_set)
print("Type of my_set:", type(my_set))
## Note: Sets automatically remove duplicate elements.
duplicate_set = {'apple', 'banana', 'apple'}
print("Set with duplicates:", duplicate_set)
## Method 2: Using the set() constructor on an iterable (like a string)
## This creates a set from the unique characters in the string.
char_set = set('hello world')
print("Set from a string:", char_set)
## Method 3: Creating an empty set
## You must use set() to create an empty set. {} creates an empty dictionary.
empty_set = set()
print("An empty set:", empty_set)
print("Type of empty_set:", type(empty_set))
파일을 저장합니다. 이제 편집기에서 터미널을 열고 (메뉴: Terminal -> New Terminal 사용 가능) 다음 명령어로 스크립트를 실행합니다.
python ~/project/set_basics.py
다음과 유사한 출력을 보게 될 것입니다. 집합 내 요소의 순서는 보장되지 않으며 중복 항목이 제거되었는지 확인하십시오.
Set created with braces: {'cherry', 'apple', 'banana'}
Type of my_set: <class 'set'>
Set with duplicates: {'banana', 'apple'}
Set from a string: {'d', 'l', 'o', 'r', 'w', ' ', 'h', 'e'}
An empty set: set()
Type of empty_set: <class 'set'>
다음으로, 기존 집합에 새 요소를 추가해 보겠습니다. add() 메서드를 사용하여 단일 요소를 추가하거나 update() 메서드를 사용하여 여러 요소를 추가할 수 있습니다.
set_basics.py 파일의 맨 아래에 다음 코드를 추가합니다.
## --- Adding elements ---
fruits = {'apple', 'banana'}
print("\nOriginal fruits set:", fruits)
## Use add() to add a single element
fruits.add('orange')
print("After adding 'orange':", fruits)
## add() has no effect if the element is already present
fruits.add('apple')
print("After adding 'apple' again:", fruits)
## Use update() to add multiple elements from an iterable (like a list)
fruits.update(['mango', 'grape'])
print("After updating with a list:", fruits)
파일을 다시 저장하고 터미널에서 업데이트된 스크립트를 실행합니다.
python ~/project/set_basics.py
출력에는 이제 요소 추가 결과가 포함됩니다.
Set created with braces: {'cherry', 'apple', 'banana'}
Type of my_set: <class 'set'>
Set with duplicates: {'banana', 'apple'}
Set from a string: {'d', 'l', 'o', 'r', 'w', ' ', 'h', 'e'}
An empty set: set()
Type of empty_set: <class 'set'>
Original fruits set: {'banana', 'apple'}
After adding 'orange': {'banana', 'orange', 'apple'}
After adding 'apple' again: {'banana', 'orange', 'apple'}
After updating with a list: {'grape', 'mango', 'banana', 'orange', 'apple'}
이제 집합을 생성하고 새 요소를 추가하여 수정하는 방법을 배웠습니다.