연산 | 시간복잡도 |
---|---|
조회 | 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]
# 리스트 복사 방법 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]
# 두 리스트 합치기 예제
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]
# 날짜 정보를 튜플로 저장하기 (수정할 필요가 없는 데이터)
date_info = (2025, 3, 21)
print("Date:", date_info) # 결과: (2025, 3, 21)
# 학생 이름과 점수를 저장하는 딕셔너리
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)
# 숫자 목록에서 중복을 제거하기 위한 세트
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}