지금까지는 변수 하나에 값 하나만 저장했습니다. 하지만 실제 프로그래밍에서는 여러 개의 값을 함께 다뤄야 하는 경우가 훨씬 많습니다. 예를 들어 학생 10명의 점수를 저장한다면 변수를 10개 만들어야 할까요? 이런 불편함을 해결하기 위해 파이썬은 리스트(list)와 튜플(tuple)이라는 자료구조를 제공합니다.
# 학생 5명의 점수를 저장
score1 = 85
score2 = 90
score3 = 78
score4 = 92
score5 = 88
# 평균 계산
average = (score1 + score2 + score3 + score4 + score5) / 5
print(average)
학생이 5명만 있어도 번거로운데, 100명이라면? 변수를 100개 만들 수는 없습니다.
# 학생 5명의 점수를 하나의 리스트로 저장
scores = [85, 90, 78, 92, 88]
# 평균 계산
average = sum(scores) / len(scores)
print(average) # 86.6
훨씬 간결하고 관리하기 쉽습니다!
리스트는 대괄호([])로 값을 묶어서 만들며, 각 값은 쉼표(,)로 구분합니다.
# 숫자 리스트
numbers = [1, 2, 3, 4, 5]
# 문자열 리스트
fruits = ['apple', 'banana', 'cherry']
# 불 값 리스트
flags = [True, False, True]
print(numbers) # [1, 2, 3, 4, 5]
print(fruits) # ['apple', 'banana', 'cherry']
print(flags) # [True, False, True]
리스트에 저장된 각각의 값을 요소(element) 또는 항목(item)이라고 부릅니다.
fruits = ['apple', 'banana', 'cherry']
# ↑ ↑ ↑
# 요소1 요소2 요소3
리스트는 모든 자료형을 저장할 수 있으며, 자료형을 섞어서 저장해도 됩니다.
# 같은 자료형
numbers = [1, 2, 3, 4, 5]
names = ['Alice', 'Bob', 'Charlie']
# 다양한 자료형 혼합
mixed = [1, 'hello', 3.14, True, [1, 2, 3]]
print(mixed) # [1, 'hello', 3.14, True, [1, 2, 3]]
마지막 요소가 리스트인 것을 주목하세요. 리스트 안에 리스트를 넣을 수도 있습니다 (중첩 리스트).
빈 리스트는 두 가지 방법으로 만들 수 있습니다.
# 방법 1: 빈 대괄호
empty_list1 = []
# 방법 2: list() 함수
empty_list2 = list()
print(empty_list1) # []
print(empty_list2) # []
print(len(empty_list1)) # 0
len() 함수로 리스트에 포함된 요소의 개수를 확인할 수 있습니다.
fruits = ['apple', 'banana', 'cherry']
print(len(fruits)) # 3
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # 5
empty = []
print(len(empty)) # 0
튜플(tuple)은 리스트처럼 요소를 일렬로 저장하지만, 한 번 만들면 수정할 수 없는 자료형입니다. 간단히 말해 읽기 전용 리스트입니다.
| 특징 | 리스트 | 튜플 |
|---|---|---|
| 기호 | [] | () |
| 수정 가능 | ✅ 가능 | ❌ 불가능 |
| 추가/삭제 | ✅ 가능 | ❌ 불가능 |
| 속도 | 느림 | 빠름 |
| 용도 | 변경 가능한 데이터 | 고정된 데이터 |
# 괄호로 묶기
numbers = (1, 2, 3, 4, 5)
fruits = ('apple', 'banana', 'cherry')
print(numbers) # (1, 2, 3, 4, 5)
print(fruits) # ('apple', 'banana', 'cherry')
# 괄호 없이도 튜플이 됨
numbers = 1, 2, 3, 4, 5
fruits = 'apple', 'banana', 'cherry'
print(numbers) # (1, 2, 3, 4, 5)
print(fruits) # ('apple', 'banana', 'cherry')
print(type(numbers)) # <class 'tuple'>
파이썬은 쉼표로 구분된 값들을 자동으로 튜플로 인식합니다.
주의: 요소가 하나만 있을 때는 반드시 쉼표를 붙여야 튜플이 됩니다.
# 잘못된 예 - 튜플이 아님
single1 = (1)
print(type(single1)) # <class 'int'> (그냥 정수)
# 올바른 예 - 튜플
single2 = (1,)
print(type(single2)) # <class 'tuple'>
# 괄호 없이도 가능
single3 = 1,
print(type(single3)) # <class 'tuple'>
# 방법 1: 빈 괄호
empty_tuple1 = ()
# 방법 2: tuple() 함수
empty_tuple2 = tuple()
print(empty_tuple1) # ()
print(empty_tuple2) # ()
print(len(empty_tuple1)) # 0
# 같은 자료형
numbers = (1, 2, 3, 4, 5)
# 다양한 자료형 혼합
mixed = (1, 'hello', 3.14, True, (1, 2, 3))
print(mixed) # (1, 'hello', 3.14, True, (1, 2, 3))
fruits = ['apple', 'banana', 'cherry']
print(fruits) # ['apple', 'banana', 'cherry']
# 요소 수정
fruits[1] = 'orange'
print(fruits) # ['apple', 'orange', 'cherry']
# 요소 추가
fruits.append('grape')
print(fruits) # ['apple', 'orange', 'cherry', 'grape']
# 요소 삭제
fruits.remove('apple')
print(fruits) # ['orange', 'cherry', 'grape']
fruits = ('apple', 'banana', 'cherry')
print(fruits) # ('apple', 'banana', 'cherry')
# 요소 수정 시도 - 에러!
fruits[1] = 'orange' # TypeError: 'tuple' object does not support item assignment
# 요소 추가 시도 - 에러!
fruits.append('grape') # AttributeError: 'tuple' object has no attribute 'append'
# 요소 삭제 시도 - 에러!
fruits.remove('apple') # AttributeError: 'tuple' object has no attribute 'remove'
튜플은 한 번 만들면 절대 변경할 수 없습니다. 이것이 리스트와의 가장 큰 차이점입니다.
변경이 필요한 데이터를 다룰 때 사용합니다.
# 쇼핑 카트 (항목 추가/삭제 가능)
shopping_cart = ['milk', 'bread', 'eggs']
shopping_cart.append('cheese')
shopping_cart.remove('bread')
# 할 일 목록 (완료된 항목 삭제)
todo_list = ['공부하기', '운동하기', '독서하기']
todo_list.remove('공부하기') # 완료!
# 게임 점수 (계속 업데이트)
scores = [100, 150, 200]
scores.append(250)
변경되면 안 되는 고정된 데이터를 다룰 때 사용합니다.
# 좌표 (x, y) - 고정값
position = (10, 20)
# RGB 색상 (빨강, 초록, 파랑) - 고정값
red = (255, 0, 0)
green = (0, 255, 0)
# 생년월일 - 변경 불가
birth_date = (1990, 5, 15) # 년, 월, 일
# 요일 - 항상 7개로 고정
weekdays = ('월', '화', '수', '목', '금', '토', '일')
# 튜플을 딕셔너리 키로 사용
locations = {
(0, 0): '원점',
(10, 20): '점A',
(30, 40): '점B'
}
print(locations[(10, 20)]) # 점A
# 리스트는 딕셔너리 키로 사용 불가
# locations[[0, 0]] = '원점' # TypeError!
list() 함수를 사용합니다.
tuple_data = (1, 2, 3, 4, 5)
list_data = list(tuple_data)
print(tuple_data) # (1, 2, 3, 4, 5)
print(list_data) # [1, 2, 3, 4, 5]
# 이제 수정 가능
list_data.append(6)
print(list_data) # [1, 2, 3, 4, 5, 6]
tuple() 함수를 사용합니다.
list_data = [1, 2, 3, 4, 5]
tuple_data = tuple(list_data)
print(list_data) # [1, 2, 3, 4, 5]
print(tuple_data) # (1, 2, 3, 4, 5)
# 이제 수정 불가
# tuple_data.append(6) # AttributeError!
# 데이터 수집 단계: 리스트 사용
data = []
data.append('item1')
data.append('item2')
data.append('item3')
# 데이터 확정 후: 튜플로 변환하여 보호
final_data = tuple(data)
print(final_data) # ('item1', 'item2', 'item3')
여러 변수에 동시에 값을 할당할 수 있습니다.
# 리스트 언패킹
numbers = [1, 2, 3]
a, b, c = numbers
print(a, b, c) # 1 2 3
# 튜플 언패킹
fruits = ('apple', 'banana', 'cherry')
x, y, z = fruits
print(x, y, z) # apple banana cherry
# 좌표 언패킹
position = (10, 20)
x, y = position
print(f'x: {x}, y: {y}') # x: 10, y: 20
def get_user_info():
name = 'Alice'
age = 25
city = 'Seoul'
return name, age, city # 튜플로 반환
# 언패킹하여 받기
user_name, user_age, user_city = get_user_info()
print(f'{user_name}, {user_age}, {user_city}')
# Alice, 25, Seoul
리스트나 튜플 안에 다른 리스트나 튜플을 넣을 수 있습니다.
# 중첩 리스트 (2차원 리스트)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0]) # [1, 2, 3]
print(matrix[1][1]) # 5
# 중첩 튜플
nested = ((1, 2), (3, 4), (5, 6))
print(nested[0]) # (1, 2)
print(nested[1][0]) # 3
# 리스트와 튜플 혼합
mixed = [(1, 2), (3, 4), (5, 6)]
print(mixed[0]) # (1, 2)