PromleeBlog
sitemap
aboutMe

posting thumbnail
파이썬 내장 자료구조 정리
Python Built-in Data Structures Summary

📅

🚀

리스트 (List) 🔗

여러 개의 데이터를 순서 있게 담을 수 있는 자료구조로, 데이터 추가, 삭제가 자유롭고 순서가 유지됩니다. 조회는 인덱스 단위로 가능하며, 복사, 슬라이싱, 정렬 등 다양한 기능을 제공합니다.
가장 많이 쓰게 되는 자료구조로, 시간복잡도는 다음과 같습니다.
연산시간복잡도
조회O(1)
추가O(1)
삭제O(n)
탐색O(n)
정렬O(n log n)
 # 과일 이름들을 저장하는 리스트 예제
fruits = ["apple", "banana", "cherry"]
 
 # 인덱스로 조회
print("First fruit:", fruits[0])  # 결과: apple
 
 # 리스트 뒤집기
reversed_fruits = fruits[::-1]
print("Reversed:", reversed_fruits)  # 결과: ['cherry', 'banana', 'apple']
 
 # 역방향으로 정렬
fruits.sort(reverse=True)
print("Reverse sorted:", fruits)  # 결과: ['cherry', 'banana', 'apple']
 
 # 정렬
fruits.sort()
print("Sorted:", fruits)  # 결과: ['apple', 'banana', 'cherry']
 
 # 리스트에 새로운 과일 추가하기
fruits.append("orange")
print("After append:", fruits)  # 결과: ['apple', 'banana', 'cherry', 'orange']
 
 # 특정 위치에 과일 추가하기
fruits.insert(1, "kiwi")
print("After insert:", fruits)  # 결과: ['apple', 'kiwi', 'banana', 'cherry', 'orange']
 
 # 리스트에서 과일 제거하기
fruits.remove("banana")
print("After remove:", fruits)  # 결과: ['apple', 'kiwi', 'cherry', 'orange']
 
 # 인덱스로 삭제
del fruits[0]
print("After delete:", fruits)  # 결과: ['kiwi', 'cherry', 'orange']
 
 # 리스트 슬라이싱
print("Sliced list:", fruits[1:])  # 결과: ['cherry', 'orange']
 
 # pop() 메서드로 마지막 요소 제거
fruits.pop()
print("After pop:", fruits)  # 결과: ['kiwi', 'cherry']

주의 - 리스트 복사 🔗

리스트를 복사할 때 주의해야 합니다. 리스트를 다른 변수에 할당하면, 실제로는 같은 리스트를 참조하게 됩니다.
 # 리스트 복사 예제
a = [1, 2, 3]
 
 # 리스트를 다른 변수에 할당
b = a
b[0] = 4
print("List a:", a)  # 결과: [4, 2, 3]
이런 경우에는
copy()
메서드를 사용하거나 슬라이싱을 통해 새로운 리스트를 생성해야 합니다.
 # 리스트 복사 방법 1: copy() 메서드 사용
a = [1, 2, 3]
b = a.copy()
b[0] = 4
print("List a:", a)  # 결과: [1, 2, 3]
 
 # 리스트 복사 방법 2: 슬라이싱 사용
a = [1, 2, 3]
b = a[:]
b[0] = 4
print("List a:", a)  # 결과: [1, 2, 3]

두 리스트 합치기 🔗

두 리스트를 합치는 방법으로는
+
연산자나
extend()
메서드를 사용할 수 있습니다.
 # 두 리스트 합치기 예제
list1 = [1, 2, 3]
list2 = [4, 5, 6]
 
 # + 연산자 사용
combined = list1 + list2
print("Combined list:", combined)  # 결과: [1, 2, 3, 4, 5, 6]
 
 # extend() 메서드 사용
list1.extend(list2)
print("Extended list:", list1)  # 결과: [1, 2, 3, 4, 5, 6]

🚀

튜플 (Tuple) 🔗

튜플은 리스트와 비슷하지만, 한 번 생성되면 수정할 수 없는(immutable) 자료구조입니다. 리스트와 마찬가지로 여러 개의 데이터를 담을 수 있으며, 함수의 반환값 등을 저장할 때 주로 사용됩니다.
 # 날짜 정보를 튜플로 저장하기 (수정할 필요가 없는 데이터)
date_info = (2025, 3, 21)
print("Date:", date_info)  # 결과: (2025, 3, 21)

🚀

딕셔너리 (Dictionary) 🔗

딕셔너리는 키와 값의 쌍으로 데이터를 저장하는 자료구조입니다. 내부적으로 해시 테이블로 구현되어 있어, 키를 이용해 빠르게 데이터를 조회할 수 있습니다.
 # 학생 이름과 점수를 저장하는 딕셔너리
student_scores = {"Alice": 90, "Bob": 80, "Charlie": 85}
 
 # 특정 학생의 점수 확인하기
print("Alice's score:", student_scores["Alice"])  # 결과: 90
 
 # 딕셔너리에 새로운 학생 추가하기
student_scores["David"] = 95
print("Updated scores:", student_scores)

🚀

세트 (Set) 🔗

세트는 집합으로, 순서가 없고 중복되지 않는 데이터를 담는 자료구조입니다. 세트는 중복 제거나 빠른 멤버십 테스트에 유용합니다. 인덱스로 접근이 불가능하며, 집합 연산(합집합, 교집합, 차집합 등)을 지원합니다.
 # 숫자 목록에서 중복을 제거하기 위한 세트
numbers = {1, 2, 3, 2, 1}
print("Unique numbers:", numbers)  # 결과: {1, 2, 3}
 
 # 세트에 새로운 원소 추가하기
numbers.add(4)
print("After add:", numbers)
 
 # 세트에서 원소 제거하기
numbers.remove(2)
print("After remove:", numbers) # 결과: {1, 3, 4}
 
 # 세트 연산: 합집합, 교집합, 차집합
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2
intersection = set1 & set2
difference = set1 - set2
print("Union:", union)  # 결과: {1, 2, 3, 4, 5}
print("Intersection:", intersection)  # 결과: {3}
print("Difference:", difference)  # 결과: {1, 2}

🚀

참고 🔗