파이썬, 자료형 [2] List & Tuple & Dictionary

sky.dev·2025년 4월 16일

Data&AI-Uni.

목록 보기
7/77
post-thumbnail

리스트(list)

파이썬에서 가장 많이 사용되는 자료구조 중 하나
여러 개의 값을 하나의 변수에 저장할 수 있다
각 값(요소, element)은 순서(인덱스)를 가지고 있다.
대괄호 []로 감싸서 만든다.

리스트의 특징

여러 개의 값을 저장: 하나의 변수에 여러 값을 저장
순서가 있다: 각 요소는 인덱스를 통해 접근
변경 가능(mutable): 리스트의 요소는 생성 후에도 변경, 추가, 삭제가 가능
다양한 자료형 저장 가능: 정수, 실수, 문자열, 다른 리스트 등 다양한 자료형을 한 리스트에 저장
중복 허용: 동일한 값을 여러 번 저장할 수 있습니다

🌳 리스트 생성

numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'cherry']
mixed = [1, 'hello', 3.14, True]

🌳 리스트 요소

fruits = ['apple', 'banana', 'cherry']
print(fruits[0])  # apple
print(fruits[1])  # banana
print(fruits[2])  # cherry

🌳 리스트 슬라이싱

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])   # [2, 3, 4]
print(numbers[:4])    # [0, 1, 2, 3]
print(numbers[5:])    # [5, 6, 7, 8, 9]
print(numbers[::2])   # [0, 2, 4, 6, 8]

List 함수

1) 추가(append(x))
리스트의 맨 끝에 새로운 요소 x를 추가.
반환 값은 None, 리스트 자체가 변경.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 출력: [1, 2, 3, 4]

2) 정렬(sort())
리스트의 요소들을 오름차순으로 정렬
원본 리스트를 직접 변경, 반환 값은 None
reverse=True 인자를 사용 내림차순으로 정렬할 수 있다

my_list = [3, 1, 4, 1, 5, 9, 2, 6]
my_list.sort()
print(my_list)      # 출력: [1, 1, 2, 3, 4, 5, 6, 9]

my_list.sort(reverse=True)
print(my_list)      # 출력: [9, 6, 5, 4, 3, 2, 1, 1]

string_list = ["apple", "banana", "cherry"]
string_list.sort()
print(string_list)  # 출력: ['apple', 'banana', 'cherry']

3) 뒤집기(reverse())
리스트의 요소 순서를 현재 순서의 반대로 뒤집는다
원본 리스트를 직접 변경, 반환 값은 None

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)  # 출력: [5, 4, 3, 2, 1]

4) 위치 반환(index(x))

my_list = [10, 20, 30, 20, 40]
index_of_20 = my_list.index(20)
print(index_of_20)  # 출력: 1

# 시작 인덱스 지정
index_from_2 = my_list.index(20, 2)
print(index_from_2)  # 출력: 3

# 존재하지 않는 요소 검색 시 에러 발생
# try:
#     my_list.index(50)
# except ValueError as e:
#     print(f"에러 발생: {e}")

5) 요소 삽입(insert(a, b))

my_list = [1, 2, 3]
my_list.insert(1, 10)  # 인덱스 1 위치에 10 삽입
print(my_list)      # 출력: [1, 10, 2, 3]

6) 요소 제거(remove(x))

my_list = [10, 20, 30, 20, 40]
my_list.remove(20)  # 첫 번째 20 제거
print(my_list)      # 출력: [10, 30, 20, 40]

7) 요소 끄집어내기(pop())

my_list = [1, 2, 3]
last_element = my_list.pop()
print(last_element)  # 출력: 3
print(my_list)      # 출력: [1, 2]

my_list = [10, 20, 30]
element_at_1 = my_list.pop(1)  # 인덱스 1의 요소 제거 및 반환
print(element_at_1)  # 출력: 20
print(my_list)      # 출력: [10, 30]

8) 특정 개수 세기(count(x))

my_list = [1, 2, 2, 3, 2, 4]
count_of_2 = my_list.count(2)
print(count_of_2)  # 출력: 3

9) 리스트 확장(extend(x))
리스트의 끝에 다른 iterable 객체 (리스트, 튜플, 문자열 등)의 모든 요소를 추가
append()와 달리, iterable 객체 자체를 추가하는 것이 아니라 그 요소들을 하나씩 추가

튜플 자료형

여러 개의 아이템을 순서대로 저장하는 자료형이라는 점에서 리스트(list)와 유사
가장 큰 차이점은 생성된 후에는 그 내용을 수정할 수 없다는 것

🌳 튜플의 생성

[1] 소괄호() 안에 콤마(,)로 요소를 구분

my_tuple = (1, 2, 3)
fruit_tuple = ("apple", "banana", "cherry")
mixed_tuple = (1, "hello", 3.14)
empty_tuple = ()  # 비어 있는 튜플

[2] 소괄호()를 생략하고 콤마(,)로 요소를 구분

my_tuple = 1, 2, 3
fruit_tuple = "apple", "banana", "cherry"
single_tuple = (5,) 
not_a_tuple = (5)

🌳튜플에서 가능한 연산

[1] 튜플 요소 인덱싱(Indexing) & 슬라이싱(Slicing)

my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0])   
print(my_tuple[1:4]) 
print(my_tuple[-1])  

[2] 연산자로 튜플 연결(Concatenation)

tuple1 = (1, 2)
tuple2 = (3, 4)
combined_tuple = tuple1 + tuple2
print(combined_tuple) 

[3] 연산자로 튜플 반복(Repetition)

my_tuple = ("a", "b")
repeated_tuple = my_tuple * 3
print(repeated_tuple)  

🌳튜플에서 불가능한 연산

[1] 튜플 요소 변경

my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # TypeError: 'tuple' object does not support item assignment

[2] 튜플 요소 삭제

my_tuple = (1, 2, 3)
# del my_tuple[1]  # TypeError: 'tuple' object does not support item deletion

🌳 튜플을 사용하는 이유

  • 더 적은 메모리 사용 및 빠른 읽기 속도
  • 데이터 안정성 확보
  • 딕셔너리 키로 사용 가능

0개의 댓글