소개
본 실습에서는 Python 의 튜플 (tuple) 에 대한 포괄적인 이해를 얻게 됩니다. 튜플을 생성하고, 인덱싱 및 슬라이싱을 사용하여 요소에 접근하는 방법을 배우며, 튜플의 불변성 (immutable nature) 을 탐구하게 됩니다. 또한, 튜플 연산자, 언패킹 (unpacking), 그리고 일반적인 내장 함수 (built-in functions) 를 사용하여 튜플 데이터를 효율적으로 다루는 연습을 하게 됩니다.
본 실습에서는 Python 의 튜플 (tuple) 에 대한 포괄적인 이해를 얻게 됩니다. 튜플을 생성하고, 인덱싱 및 슬라이싱을 사용하여 요소에 접근하는 방법을 배우며, 튜플의 불변성 (immutable nature) 을 탐구하게 됩니다. 또한, 튜플 연산자, 언패킹 (unpacking), 그리고 일반적인 내장 함수 (built-in functions) 를 사용하여 튜플 데이터를 효율적으로 다루는 연습을 하게 됩니다.
이 단계에서는 튜플을 생성하고 요소에 접근하는 방법을 배웁니다. 튜플은 순서가 있으며, 생성 후 내용을 변경할 수 없는 불변 (immutable) 항목들의 모음입니다.
먼저, WebIDE 왼쪽의 파일 탐색기 (file explorer) 를 찾으십시오. tuple_basics.py라는 파일을 찾아 엽니다. 코드는 이 파일에 작성할 것입니다.
몇 가지 다른 유형의 튜플을 생성하는 것부터 시작하겠습니다. 다음 코드를 tuple_basics.py에 추가하십시오:
## Create an empty tuple
empty_tuple = ()
print("Empty tuple:", empty_tuple)
print("Type of empty_tuple:", type(empty_tuple))
## Create a tuple with a single element (note the trailing comma)
single_element_tuple = (50,)
print("\nSingle element tuple:", single_element_tuple)
print("Type of single_element_tuple:", type(single_element_tuple))
## Create a tuple with multiple elements
fruits = ("apple", "banana", "cherry")
print("\nFruits tuple:", fruits)
## Create a tuple from a list using the tuple() constructor
numbers_list = [1, 2, 3, 4]
numbers_tuple = tuple(numbers_list)
print("\nTuple from list:", numbers_tuple)
코드를 추가한 후 파일을 저장하십시오 (단축키 Ctrl+S 사용 가능). 그런 다음 WebIDE 하단의 터미널을 열고 다음 명령어로 스크립트를 실행하십시오:
python tuple_basics.py
다음과 같은 출력 결과를 보게 될 것이며, 이는 튜플의 생성 및 유형이 올바르게 확인되었음을 의미합니다:
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
이제 튜플 내의 요소에 접근하는 방법을 배워보겠습니다. 인덱싱 (0 부터 시작) 을 사용하여 단일 요소를 가져올 수 있으며, 슬라이싱 (slicing) 을 사용하여 요소의 하위 시퀀스 (sub-sequence) 를 가져올 수 있습니다.
다음 코드를 tuple_basics.py 파일의 끝에 추가하십시오:
## Define a sample tuple for accessing elements
my_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print("\nOriginal tuple:", my_tuple)
## Access elements using indexing
print("First element (index 0):", my_tuple[0])
print("Last element (index -1):", my_tuple[-1])
## Access elements using slicing
print("Elements from index 1 to 3:", my_tuple[1:4])
print("Elements from index 2 to the end:", my_tuple[2:])
print("Reverse the tuple:", my_tuple[::-1])
파일을 다시 저장하고 터미널에서 스크립트를 실행하십시오:
python tuple_basics.py
전체 출력 결과에는 이제 튜플 요소 접근 결과가 포함됩니다:
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
Original tuple: ('p', 'y', 't', 'h', 'o', 'n')
First element (index 0): p
Last element (index -1): n
Elements from index 1 to 3: ('y', 't', 'h')
Elements from index 2 to the end: ('t', 'h', 'o', 'n')
Reverse the tuple: ('n', 'o', 'h', 't', 'y', 'p')
이제 성공적으로 튜플을 생성하고 요소에 접근했습니다.
튜플의 핵심적인 특징은 불변성 (immutability) 입니다. 이는 튜플이 생성된 후에는 그 내용을 변경하거나, 추가하거나, 제거할 수 없음을 의미합니다. 이 단계에서는 튜플을 수정하려고 할 때 어떤 일이 발생하는지 확인하고, 새로운 튜플을 생성하여 "수정"을 달성하는 올바른 방법을 배웁니다.
파일 탐색기에서 tuple_modification.py 파일을 여십시오.
먼저, 튜플의 요소를 직접 변경해 보겠습니다. 다음 코드를 tuple_modification.py에 추가하십시오. 수정 시도를 하는 줄은 주석 처리되어 있습니다.
my_tuple = ('a', 'b', 'c', 'd', 'e')
print("Original tuple:", my_tuple)
## The following line will cause a TypeError because tuples are immutable.
## You can uncomment it to see the error for yourself.
## my_tuple[0] = 'f'
만약 마지막에서 두 번째 줄의 주석을 해제하고 코드를 실행하면, Python 은 멈추고 TypeError: 'tuple' object does not support item assignment 오류를 표시할 것입니다.
튜플을 제자리에서 (in place) 수정할 수 없으므로, 해결책은 원하는 변경 사항을 포함하는 새로운 튜플을 생성하는 것입니다. 이는 슬라이싱과 연결 (concatenation, + 연산자) 을 사용하여 수행할 수 있습니다.
요소를 "대체"하는 방법을 확인하기 위해 다음 코드를 tuple_modification.py 파일 끝에 추가하십시오:
## "Modify" a tuple by creating a new one
## Concatenate a new single-element tuple ('f',) with a slice of the original tuple
modified_tuple = ('f',) + my_tuple[1:]
print("New 'modified' tuple:", modified_tuple)
print("Original tuple is unchanged:", my_tuple)
마찬가지로, 해당 요소를 제외하는 새 튜플을 생성하여 요소를 "삭제"할 수 있습니다. 이 코드를 파일에 추가하십시오:
## "Delete" an element by creating a new tuple
## Concatenate the slice before the element with the slice after the element
tuple_after_deletion = my_tuple[:2] + my_tuple[3:] ## Excludes element at index 2 ('c')
print("\nNew tuple after 'deletion':", tuple_after_deletion)
파일을 저장하고 터미널에서 실행하십시오:
python tuple_modification.py
출력 결과는 원본 튜플은 그대로 유지된 채 새로운 튜플들이 생성되었음을 보여줄 것입니다:
Original tuple: ('a', 'b', 'c', 'd', 'e')
New 'modified' tuple: ('f', 'b', 'c', 'd', 'e')
Original tuple is unchanged: ('a', 'b', 'c', 'd', 'e')
New tuple after 'deletion': ('a', 'b', 'd', 'e')
이 단계는 튜플의 불변성 특성과 이 제약 사항을 우회하는 표준적인 방법을 강조합니다.
Python 은 튜플 작업을 위한 몇 가지 유용한 연산자를 제공합니다. 또한, 튜플 요소를 변수에 할당하는 강력한 기능인 튜플 언패킹 (tuple unpacking) 에 대해서도 배웁니다.
파일 탐색기에서 tuple_operators.py 파일을 여십시오.
연결 (+), 반복 (*), 포함 여부 (in) 연산자를 살펴보겠습니다. 다음 코드를 tuple_operators.py에 추가하십시오:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
## Concatenation (+)
concatenated_tuple = tuple1 + tuple2
print("Concatenated:", concatenated_tuple)
## Repetition (*)
repeated_tuple = tuple1 * 3
print("Repeated:", repeated_tuple)
## Membership (in)
is_present = 'b' in tuple2
print("\nIs 'b' in tuple2?", is_present)
is_absent = 5 in tuple1
print("Is 5 in tuple1?", is_absent)
파일을 저장하고 터미널에서 실행하십시오:
python tuple_operators.py
이러한 연산의 결과를 볼 수 있습니다:
Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Is 'b' in tuple2? True
Is 5 in tuple1? False
다음으로, 튜플 언패킹을 살펴보겠습니다. 이는 단일의 읽기 쉬운 줄에서 튜플의 요소들을 여러 변수에 할당할 수 있게 해줍니다. 변수의 개수는 튜플의 요소 개수와 일치해야 합니다.
다음 코드를 tuple_operators.py 파일 끝에 추가하십시오:
## Tuple unpacking
person_info = ("Alice", 30, "Engineer")
name, age, profession = person_info
print("\nOriginal info tuple:", person_info)
print("Unpacked Name:", name)
print("Unpacked Age:", age)
print("Unpacked Profession:", profession)
파일을 다시 저장하고 스크립트를 실행하십시오:
python tuple_operators.py
이제 출력 결과에 언패킹된 변수들이 포함될 것입니다:
Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Is 'b' in tuple2? True
Is 5 in tuple1? False
Original info tuple: ('Alice', 30, 'Engineer')
Unpacked Name: Alice
Unpacked Age: 30
Unpacked Profession: Engineer
튜플 언패킹은 여러 값을 반환하는 함수 (함수는 종종 튜플 형태로 반환함) 를 다룰 때 특히 유용합니다.
마지막 단계에서는 튜플에 대해 작동하는 일반적인 내장 함수 (built-in functions) 와 메서드 (methods) 를 사용하는 방법을 배웁니다. 튜플에는 주로 count()와 index()라는 두 가지 메서드가 있으며, 많은 범용 함수들과 함께 사용될 수 있습니다.
파일 탐색기에서 tuple_functions.py 파일을 여십시오.
튜플 메서드부터 시작하겠습니다. count()는 특정 요소가 나타나는 횟수를 반환하고, index()는 요소가 처음 나타나는 인덱스를 반환합니다.
다음 코드를 tuple_functions.py에 추가하십시오:
my_tuple = (1, 5, 2, 8, 5, 3, 5, 9)
print("Tuple:", my_tuple)
## count() method
count_of_5 = my_tuple.count(5)
print("Count of 5:", count_of_5)
## index() method
index_of_8 = my_tuple.index(8)
print("Index of 8:", index_of_8)
이제 len(), max(), min(), sum(), sorted()와 같이 튜플에서 매우 유용한 몇 가지 내장 함수를 사용해 보겠습니다.
다음 코드를 tuple_functions.py 파일 끝에 추가하십시오:
number_tuple = (10, 5, 20, 15, 30, 5)
print("\nNumber tuple:", number_tuple)
## len() function
print("Length:", len(number_tuple))
## max() and min() functions
print("Maximum value:", max(number_tuple))
print("Minimum value:", min(number_tuple))
## sum() function (for numeric tuples)
print("Sum of elements:", sum(number_tuple))
## sorted() function (returns a new sorted list)
sorted_list = sorted(number_tuple)
print("Sorted list from tuple:", sorted_list)
sorted() 함수는 튜플이 아닌 새로운 리스트 (list) 를 반환한다는 점에 유의하십시오. 정렬된 튜플이 필요한 경우, tuple(sorted_list)를 사용하여 결과를 다시 튜플로 변환할 수 있습니다.
파일을 저장하고 터미널에서 실행하십시오:
python tuple_functions.py
출력 결과는 다음과 같아야 합니다:
Tuple: (1, 5, 2, 8, 5, 3, 5, 9)
Count of 5: 3
Index of 8: 3
Number tuple: (10, 5, 20, 15, 30, 5)
Length: 6
Maximum value: 30
Minimum value: 5
Sum of elements: 85
Sorted list from tuple: [5, 5, 10, 15, 20, 30]
이제 튜플을 검사하고 분석하기 위한 중요한 메서드와 함수들을 사용하는 방법을 배웠습니다.
본 실습 (lab) 을 통해 Python 튜플 (tuple) 사용에 대한 견고한 기초를 다졌습니다. 다양한 방법으로 튜플을 생성하는 방법과 인덱싱 (indexing) 및 슬라이싱 (slicing) 을 사용하여 요소에 접근하는 방법을 배웠습니다. 튜플의 불변성 (immutability) 이라는 핵심 개념을 탐구하고, "수정" 작업을 수행하기 위해 새로운 튜플을 생성하는 연습을 했습니다. 또한, 튜플 데이터 작업을 위한 일반적인 튜플 연산자 (+, *), 튜플 언패킹 (unpacking) 의 편리성, 그리고 내장 메서드 (count(), index()) 및 함수 (len(), max(), sorted()) 의 유용성에 대해서도 익혔습니다.