12일 차: Python Programming

발행: (2025년 12월 2일 오후 10:11 GMT+9)
4 min read
원문: Dev.to

Source: Dev.to

PART-1: LIST – 고급 개념

List Comprehension

  • 조건 포함

Nested List Comprehension

  • 중첩 리스트 컴프리헨션

List Slicing

  • 리스트 슬라이싱

Important List Methods

예시:

# Example of using list methods
my_list = [1, 2, 3, 4, 5]
my_list.append(6)          # Add an element
my_list.extend([7, 8])     # Extend with another list
my_list.insert(0, 0)       # Insert at the beginning
my_list.remove(3)          # Remove first occurrence of 3
my_list.pop()              # Remove and return the last item
my_list.clear()            # Empty the list

Cloning a List

original = [1, 2, 3]
clone = original[:]        # Shallow copy using slicing
# or
clone = list(original)     # Using the list constructor

PART-2: TUPLE – 고급 개념

Tuple Unpacking

  • 튜플 언패킹
point = (10, 20)
x, y = point

Tuple with * (Extended Unpacking)

    • 를 사용한 튜플 (확장 언패킹)
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers

Why Tuple Is Faster?

  • 불변성 → 연속 메모리에 저장
  • 리스트보다 빠른 반복
  • 고정된 데이터에 이상적 (예: 위도/경도, 설정)

Convert List to Tuple

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

PART-3: SET – 고급 개념

Set Operations

  • 셋 연산
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)   # union -> {1, 2, 3, 4, 5}
print(A & B)   # intersection -> {3}
print(A - B)   # difference -> {1, 2}

Remove Duplicates from List Using Set

  • 셋을 이용해 리스트 중복 제거
my_list = [1, 2, 2, 3, 4, 4]
unique = list(set(my_list))   # [1, 2, 3, 4] (order not guaranteed)

Add & Remove Elements

  • 요소 추가 및 제거
s = {1, 2, 3}
s.add(4)          # {1, 2, 3, 4}
s.discard(2)      # {1, 3, 4}
s.remove(3)       # {1, 4}

Set Comprehension

  • 셋 컴프리헨션
squared = {x**2 for x in range(5)}   # {0, 1, 4, 9, 16}

PART-4: DICTIONARY – 고급 개념

Dictionary Comprehension

  • 딕셔너리 컴프리헨션
squares = {x: x*x for x in range(5)}   # {0:0, 1:1, 2:4, 3:9, 4:16}

Looping Through Dictionary

  • 딕셔너리 순회
d = {'a': 1, 'b': 2}
for key, value in d.items():
    print(key, value)

Merging Two Dictionaries

  • 두 딕셔너리 병합
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
merged = {**d1, **d2}   # {'a': 1, 'b': 3, 'c': 4}
# Python 3.9+ alternative:
merged = d1 | d2

Dictionary Methods

  • dict.get(key, default)
  • dict.keys(), dict.values(), dict.items()
  • dict.update(other_dict)
  • dict.pop(key), dict.popitem()
  • dict.clear()

Using Dictionary as Counter

  • 딕셔너리를 카운터로 사용
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = {}
for w in words:
    counter[w] = counter.get(w, 0) + 1
# counter -> {'apple': 3, 'banana': 2, 'orange': 1}

PART-5: Collections Module (Important for Interviews)

Counter

  • Counter
from collections import Counter
cnt = Counter(['a', 'b', 'a', 'c', 'b', 'a'])
# Counter({'a': 3, 'b': 2, 'c': 1})

defaultdict

  • defaultdict
from collections import defaultdict
dd = defaultdict(list)
dd['key'].append(1)   # automatically creates a list for 'key'

deque

  • deque
from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0)      # deque([0, 1, 2, 3])
dq.pop()              # 3

OrderedDict

  • OrderedDict
from collections import OrderedDict
od = OrderedDict()
od['first'] = 1
od['second'] = 2
# Preserves insertion order (Python 3.7+ dict does this by default)

PART-6: Interview Programs Using Collections

Find the Most Repeated Element

  • 가장 많이 반복된 요소 찾기
from collections import Counter
def most_common(lst):
    return Counter(lst).most_common(1)[0][0]

print(most_common([1, 2, 2, 3, 3, 3]))   # 3

Reverse a List Without Using reverse()

  • reverse() 없이 리스트 뒤집기
lst = [1, 2, 3, 4]
reversed_lst = lst[::-1]   # [4, 3, 2, 1]

Merge Two Lists into a Dictionary

  • 두 리스트를 딕셔너리로 병합
keys = ['a', 'b', 'c']
values = [1, 2, 3]
merged_dict = dict(zip(keys, values))   # {'a': 1, 'b': 2, 'c': 3}

Remove Duplicates While Preserving Order

  • 순서를 유지하면서 중복 제거
def dedupe(seq):
    seen = set()
    return [x for x in seq if not (x in seen or seen.add(x))]

print(dedupe([3, 1, 2, 3, 2, 1]))   # [3, 1, 2]

Convert Dictionary to List of Tuples

  • 딕셔너리를 튜플 리스트로 변환
d = {"a": 1, "b": 2}
print(list(d.items()))   # [('a', 1), ('b', 2)]
Back to Blog

관련 글

더 보기 »

Bf-트리: 페이지 장벽을 깨다

안녕하세요, 저는 Maneshwar입니다. 저는 FreeDevTools – 온라인 오픈‑소스 허브를 개발하고 있습니다. 이 허브는 dev tools, cheat codes, 그리고 TLDRs를 한 곳에 모아 쉽게 이용할 수 있게 합니다.