lst = [1, 2, 3]
lst = list() # 빈 리스트
lst = list("abc") # ['a', 'b', 'c']
lst = list(range(5)) # [0, 1, 2, 3, 4]
lst = [0] * 5 # [0, 0, 0, 0, 0]
lst = [i for i in range(5)] # 컴프리헨션
lst = [0, 1, 2, 3, 4, 5]
# 인덱싱
lst[0] # 0 (첫 번째)
lst[-1] # 5 (마지막)
lst[-2] # 4 (뒤에서 두 번째)
# 슬라이싱 [start:end:step]
lst[1:4] # [1, 2, 3]
lst[:3] # [0, 1, 2]
lst[3:] # [3, 4, 5]
lst[::2] # [0, 2, 4] (2칸씩)
lst[::-1] # [5, 4, 3, 2, 1, 0] (역순)
lst[1:5:2] # [1, 3]
# 슬라이싱으로 수정
lst[1:3] = [10, 20] # [0, 10, 20, 3, 4, 5]
lst[1:3] = [10, 20, 30] # 길이 다르게도 가능
lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4] 맨 뒤에 추가
lst.insert(0, 0) # [0, 1, 2, 3, 4] 특정 위치에 추가
lst.insert(-1, 3.5) # 마지막 앞에 삽입
lst.extend([5, 6]) # [1, 2, 3, 5, 6] 리스트 확장
lst += [7, 8] # 동일
# append vs extend
lst.append([4, 5]) # [1, 2, 3, [4, 5]] - 리스트가 요소로
lst.extend([4, 5]) # [1, 2, 3, 4, 5] - 요소들이 추가
lst = [1, 2, 3, 4, 5]
lst.pop() # 5 반환, [1, 2, 3, 4]
lst.pop(0) # 1 반환, [2, 3, 4, 5]
lst.remove(3) # [1, 2, 4, 5] (첫 번째 3 삭제)
del lst[0] # [2, 3, 4, 5]
del lst[1:3] # 슬라이싱 삭제
lst.clear() # [] (전체 삭제)
# 조건부 삭제 (컴프리헨션)
lst = [x for x in lst if x != 3]
lst = [1, 2, 3, 2, 4]
# 존재 여부
2 in lst # True
5 not in lst # True
# 인덱스 찾기
lst.index(2) # 0 (첫 번째 위치)
lst.index(2, 1) # 3 (인덱스 1부터 검색)
# 개수 세기
lst.count(2) # 2
lst = [3, 1, 4, 1, 5, 9, 2]
# sort(): 원본 변경
lst.sort() # [1, 1, 2, 3, 4, 5, 9]
lst.sort(reverse=True) # [9, 5, 4, 3, 2, 1, 1]
# sorted(): 새 리스트 반환 (원본 유지)
new = sorted(lst)
new = sorted(lst, reverse=True)
# key로 정렬 기준 지정
words = ["banana", "apple", "Cherry"]
sorted(words) # 기본: 대소문자 구분
sorted(words, key=str.lower) # 대소문자 무시
sorted(words, key=len) # 길이순
# 딕셔너리 리스트 정렬
users = [{"name": "Bob", "age": 20}, {"name": "Alice", "age": 25}]
sorted(users, key=lambda x: x["age"]) # 나이순
sorted(users, key=lambda x: x["name"]) # 이름순
# 다중 기준 정렬
sorted(users, key=lambda x: (x["age"], x["name"]))
lst = [1, 2, 3, 4, 5]
# reverse(): 원본 변경
lst.reverse() # [5, 4, 3, 2, 1]
# reversed(): 반복자 반환
list(reversed(lst)) # [5, 4, 3, 2, 1]
# 슬라이싱
lst[::-1] # [5, 4, 3, 2, 1] (새 리스트)
lst = [1, 2, [3, 4]]
# 얕은 복사 (1레벨만)
copy1 = lst[:]
copy2 = lst.copy()
copy3 = list(lst)
# 깊은 복사 (중첩 구조 포함)
import copy
deep = copy.deepcopy(lst)
# 주의: 얕은 복사는 내부 객체 공유
copy1[2][0] = 99 # lst[2][0]도 99로 변경!
# 기본
[x for x in range(5)] # [0, 1, 2, 3, 4]
[x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# 조건 필터링
[x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
# if-else
["짝" if x % 2 == 0 else "홀" for x in range(5)]
# 중첩 반복
[(i, j) for i in range(3) for j in range(3)]
# 2차원 리스트 생성
[[0] * 3 for _ in range(3)] # [[0,0,0], [0,0,0], [0,0,0]]
# 2차원 리스트 평탄화
matrix = [[1, 2], [3, 4], [5, 6]]
[x for row in matrix for x in row] # [1, 2, 3, 4, 5, 6]
lst = [3, 1, 4, 1, 5]
len(lst) # 5 (길이)
sum(lst) # 14 (합계)
min(lst) # 1 (최솟값)
max(lst) # 5 (최댓값)
# 인덱스와 함께 순회
for i, v in enumerate(lst):
print(i, v)
for i, v in enumerate(lst, start=1): # 1부터 시작
print(i, v)
# 여러 리스트 동시 순회
a, b = [1, 2, 3], [4, 5, 6]
for x, y in zip(a, b):
print(x, y)
# all / any
all([True, True, False]) # False (모두 True?)
any([True, False, False]) # True (하나라도 True?)
# map
list(map(str, [1, 2, 3])) # ['1', '2', '3']
list(map(lambda x: x*2, [1, 2, 3])) # [2, 4, 6]
# filter
list(filter(lambda x: x > 2, [1, 2, 3, 4])) # [3, 4]
# 리스트 중복 제거 (순서 유지)
lst = [1, 2, 2, 3, 1, 4]
list(dict.fromkeys(lst)) # [1, 2, 3, 4]
# 리스트 중복 제거 (순서 무시)
list(set(lst)) # [1, 2, 3, 4] (순서 보장 안됨)
# 2차원 리스트 전치 (행↔열)
matrix = [[1, 2, 3], [4, 5, 6]]
list(zip(*matrix)) # [(1, 4), (2, 5), (3, 6)]
# 리스트 회전
lst = [1, 2, 3, 4, 5]
lst[1:] + lst[:1] # [2, 3, 4, 5, 1] (왼쪽 회전)
lst[-1:] + lst[:-1] # [5, 1, 2, 3, 4] (오른쪽 회전)
# 최댓값 인덱스
lst.index(max(lst))
# n개씩 묶기
def chunk(lst, n):
return [lst[i:i+n] for i in range(0, len(lst), n)]
chunk([1,2,3,4,5,6], 2) # [[1,2], [3,4], [5,6]]
# 요소 빈도 세기
from collections import Counter
Counter([1, 1, 2, 3, 3, 3]) # {3: 3, 1: 2, 2: 1}