파이썬 기초 외전 · 01 · 최종본
알고리즘 문제풀이 · 실전 자동화 · 메서드 · 내장 함수 · 표준 라이브러리 · 핵심 개념 총정리
알고리즘과 실전에서 자주 쓰는
파이썬 메서드·함수·라이브러리·핵심 개념 총정리
이 외전은 본편 12장을 끝낸 뒤 “실제로는 무엇을 더 자주 쓰게 될까?”라는 질문에 답하기 위해 만든 실전형 보충편입니다. 단순히 메서드 이름만 늘어놓는 것이 아니라 언제 쓰는지, 무엇과 헷갈리는지, 어떤 개념과 연결되는지까지 함께 정리합니다. 문자열 메서드, 리스트·딕셔너리·집합, 핵심 내장 함수, 알고리즘용 표준 라이브러리, 파일 처리와 자동화 도구, 그리고 mutable/immutable, truthy/falsy, context manager, iterator/generator 같은 중요한 개념까지 한 번에 훑습니다.
이 외전에서 배우는 것
- 문자열, 리스트, 딕셔너리, 집합에서 자주 쓰는 메서드를 우선순위 중심으로 정리합니다.
- 초보자가 실제로 자주 마주치는 input(), print(), 형변환, 포함 검사, 복사 개념을 묶어서 이해합니다.
- 알고리즘 문제풀이에 많이 쓰는 Counter, deque, heapq, bisect, itertools, math를 연결해서 익힙니다.
- 실전 자동화에서 자주 만나는 파일 처리, 경로, JSON, 시간, 로깅, 네트워크, 브라우저 열기 도구를 익힙니다.
- 메서드보다 더 중요한 mutable/immutable, truthy/falsy, context manager, 예외 처리, iterator/generator 관계를 함께 정리합니다.
이 외전을 끝내면
- 문제를 보고 어떤 메서드나 라이브러리를 먼저 떠올려야 하는지 감이 생깁니다.
- 문자열은 immutable이라는 점, 리스트 복사는 얕은 복사와 깊은 복사를 구분해야 한다는 점을 설명할 수 있습니다.
- 입력, 형변환, 정렬, 포함 검사, 빈도 계산, 큐 처리, 힙 처리, JSON 직렬화 같은 핵심 흐름을 실전적으로 연결할 수 있습니다.
- 다음 단계인 외부 라이브러리, 자동화 스크립트, 작은 프로젝트, 코딩테스트 입문으로 자연스럽게 확장할 수 있습니다.
먼저 큰 지도로 보기
문자열/자료구조
split, join, replace, get, sorted, set 연산, 복사 개념
내장 함수
input, print, int, float, len, range, enumerate, zip, map, filter
알고리즘 라이브러리
Counter, deque, heapq, bisect, itertools, math
실전 자동화
open, json, pathlib, logging, argparse, subprocess, glob, tempfile, zipfile
1
문자열 메서드와 immutable 개념
문자열 파트에서 가장 중요한 사실은 문자열은 immutable이라는 점입니다. 즉 upper(), lower(), replace(), strip(), split(), splitlines(), partition() 같은 메서드는 원본을 바꾸는 것이 아니라 새 값을 돌려줍니다.
자주 쓰는 문자열 메서드
자르기/분리 : split(), splitlines(), partition()
합치기/치환 : join(), replace()
공백 처리 : strip(), lstrip(), rstrip()
탐색/검사 : find(), index(), count(), startswith(), endswith()
대소문자/표기 : upper(), lower(), capitalize(), title(), swapcase()
문자 판별 : isalpha(), isdigit(), isalnum(), isspace()
형식 맞추기 : zfill(), center(), ljust(), rjust(), format(), f-string
합치기/치환 : join(), replace()
공백 처리 : strip(), lstrip(), rstrip()
탐색/검사 : find(), index(), count(), startswith(), endswith()
대소문자/표기 : upper(), lower(), capitalize(), title(), swapcase()
문자 판별 : isalpha(), isdigit(), isalnum(), isspace()
형식 맞추기 : zfill(), center(), ljust(), rjust(), format(), f-string
코드로 빠르게 보기
text = " hello world\npython 123 "
print(text.strip())
print(text.upper())
print(text.split())
print(text.splitlines())
print(text.partition("world"))
print("7".zfill(3))
print("abc".capitalize())
print("hello world".title())
print("PyThOn".swapcase())
print("abc123".isalnum())
print(" ".isspace())
name = "민수"
print(f"안녕하세요, {name}님")
정리하면 문자열 메서드에서 가장 먼저 기억할 것은 “원본 변경이 아니라 새 문자열 반환”이라는 점입니다. 이 감각이 있으면 왜 text.upper()만 쓰고 끝나면 원본이 그대로인지도 자연스럽게 이해할 수 있습니다.
리스트·튜플·시퀀스 핵심
추가/삭제 : append(), extend(), insert(), remove(), pop(), clear(), del
정렬/뒤집기 : sort(), sorted(), reverse(), reversed()
탐색/복사 : count(), index(), copy()
변환 함수 : list(), tuple()
공통 개념 : 슬라이싱, 음수 인덱싱, 언패킹, in / not in, 리스트 컴프리헨션
정렬/뒤집기 : sort(), sorted(), reverse(), reversed()
탐색/복사 : count(), index(), copy()
변환 함수 : list(), tuple()
공통 개념 : 슬라이싱, 음수 인덱싱, 언패킹, in / not in, 리스트 컴프리헨션
nums = [3, 1, 4, 1, 5]
print(nums[-1])
print(4 in nums)
print(9 not in nums)
print(nums.count(1))
print(nums.index(4))
copy_nums = nums.copy()
print(sorted(nums))
nums.reverse()
del nums[0]
letters = list("python")
point = tuple([10, 20])
얕은 복사와 깊은 복사
리스트를 다루다 보면 메서드보다 더 중요한 것이 복사 개념입니다. 특히 중첩 리스트에서는 얕은 복사와 깊은 복사를 구분해야 합니다.
import copy
board = [[1, 2], [3, 4]]
shallow = board.copy()
deep = copy.deepcopy(board)
board[0][0] = 99
print(shallow) # 내부 리스트 영향 받음
print(deep) # 깊은 복사는 안전
2차원 리스트 초기화나 복사에서 자주 실수하므로, 자료형 파트에서는 메서드 암기만큼 복사 감각이 중요합니다.
딕셔너리 핵심
조회 : get(), keys(), values(), items()
수정 : update(), setdefault(), pop(), popitem(), clear(), copy(), fromkeys()
표현식 : dict comprehension
수정 : update(), setdefault(), pop(), popitem(), clear(), copy(), fromkeys()
표현식 : dict comprehension
student = {"name": "민수", "age": 20}
print(student.get("score", 0))
student.update({"score": 95})
print(student.pop("age"))
print(dict.fromkeys(["a", "b"], 0))
lengths = {name: len(name) for name in ["kim", "lee"]}
print(lengths)
딕셔너리의 copy()도 기본적으로 얕은 복사입니다. 값으로 리스트나 딕셔너리 같은 mutable 객체가 들어 있으면 내부 객체는 함께 참조될 수 있다는 점을 기억하면 좋습니다.
집합 핵심
기본 조작 : add(), remove(), discard(), clear(), copy(), update()
집합 연산 : union(), intersection(), difference(), symmetric_difference()
관계 비교 : issubset(), issuperset()
핵심 쓰임 : 중복 제거, 빠른 포함 검사, 공통 원소 찾기
집합 연산 : union(), intersection(), difference(), symmetric_difference()
관계 비교 : issubset(), issuperset()
핵심 쓰임 : 중복 제거, 빠른 포함 검사, 공통 원소 찾기
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
print({1, 2}.issubset(a))
print(a.issuperset({1, 2}))
초보자가 가장 자주 쓰는 내장 함수
입출력/형변환
print(), input(), int(), float(), str(), list(), tuple(), dict(), set()
print(), input(), int(), float(), str(), list(), tuple(), dict(), set()
반복/집계
len(), range(), sum(), max(), min(), enumerate(), zip()
len(), range(), sum(), max(), min(), enumerate(), zip()
계산/판별
abs(), round(), pow(), isinstance(), type()
abs(), round(), pow(), isinstance(), type()
데이터 처리
map(), filter(), lambda, sorted()
map(), filter(), lambda, sorted()
조건 판별
all(), any()
all(), any()
문자/진법
ord(), chr(), bin(), oct(), hex(), divmod()
ord(), chr(), bin(), oct(), hex(), divmod()
name = input("이름: ")
age = int("20")
height = float("172.5")
text_age = str(age)
print(name, age, height, text_age)
print(int("11", 2))
print(int("1A", 16))
print(list("abc"))
print(tuple([1, 2]))
print(dict([("a", 1)]))
print(set([1, 1, 2]))
print(abs(-7), round(3.14159, 2), pow(2, 5))
초보자에게는 입력 → 형변환 → 처리 → 출력 흐름이 특히 중요합니다. 이때 input()은 문자열을 반환하고, 필요하면 int(), float(), str()로 바꾸어 써야 합니다.
헷갈리기 쉬운 메서드·함수 비교
sort() vs sorted()
sort()는 리스트 원본을 바꾸고, sorted()는 새 정렬 결과를 반환합니다.
sort()는 리스트 원본을 바꾸고, sorted()는 새 정렬 결과를 반환합니다.
reverse() vs reversed()
reverse()는 원본 변경, reversed()는 반복자 반환입니다.
reverse()는 원본 변경, reversed()는 반복자 반환입니다.
dict.get() vs dict[key]
get()은 기본값을 줄 수 있고, []는 키가 없으면 KeyError가 납니다.
get()은 기본값을 줄 수 있고, []는 키가 없으면 KeyError가 납니다.
remove() vs discard()
리스트의 remove()는 값을 지우고, 집합의 discard()는 값이 없어도 조용히 넘어갑니다.
리스트의 remove()는 값을 지우고, 집합의 discard()는 값이 없어도 조용히 넘어갑니다.
partition() vs split()
partition()은 구분자를 기준으로 3조각, split()은 여러 조각의 리스트를 만듭니다.
partition()은 구분자를 기준으로 3조각, split()은 여러 조각의 리스트를 만듭니다.
map/filter/lambda vs comprehension
둘 다 변환과 필터링에 쓰이지만, 초보자에게는 comprehension이 더 직관적인 경우가 많습니다.
둘 다 변환과 필터링에 쓰이지만, 초보자에게는 comprehension이 더 직관적인 경우가 많습니다.
json.dumps/loads vs dump/load
dumps/loads는 문자열, dump/load는 파일 객체를 다룹니다.
dumps/loads는 문자열, dump/load는 파일 객체를 다룹니다.
os.path.join() vs Path /
문자열 기반 조합은 os.path.join(), 객체 기반 조합은 pathlib.Path가 읽기 쉽습니다.
문자열 기반 조합은 os.path.join(), 객체 기반 조합은 pathlib.Path가 읽기 쉽습니다.
with open()의 의미
파일을 쓰고 나서 자동으로 닫아 주므로, 직접 close()를 빼먹을 위험을 줄입니다.
파일을 쓰고 나서 자동으로 닫아 주므로, 직접 close()를 빼먹을 위험을 줄입니다.
알고리즘용 collections / heapq / bisect
from collections import Counter, defaultdict, deque
import heapq
from bisect import bisect_left, bisect_right
counter = Counter("banana")
print(counter.most_common(1))
groups = defaultdict(list)
groups["A"].append(10)
dq = deque([1, 2, 3])
dq.appendleft(0)
print(dq.popleft())
nums = [5, 1, 3]
heapq.heapify(nums)
heapq.heappush(nums, 2)
print(heapq.heappop(nums))
arr = [1, 3, 3, 7]
print(bisect_left(arr, 3))
print(bisect_right(arr, 3))
Counter는 빈도 계산, defaultdict는 기본값 자동 생성, deque는 양쪽 삽입/삭제, heapq는 우선순위 큐, bisect는 정렬된 배열에서 위치 찾기에 강합니다.
itertools / math
from itertools import permutations, combinations, product, accumulate, chain
from math import gcd, lcm, factorial, sqrt, isqrt, ceil, floor, inf, log, exp
print(list(permutations([1, 2, 3], 2)))
print(list(combinations([1, 2, 3], 2)))
print(list(product([1, 2], repeat=2)))
print(list(accumulate([1, 2, 3, 4])))
print(list(chain([1, 2], [3, 4])))
print(gcd(12, 18), lcm(12, 18))
print(factorial(5), sqrt(16), isqrt(17))
print(ceil(3.2), floor(3.8), inf)
print(round(log(exp(2)), 2))
itertools는 경우의 수와 반복 조합에 강하고, math는 최대공약수·최소공배수·정수 제곱근·무한대 초기값 처리처럼 문제풀이에서 반복적으로 등장합니다.
실전 표준 라이브러리: 파일, 경로, 데이터, 시간, 자동화
시스템 입력
sys.stdin.readline, sys.argv
sys.stdin.readline, sys.argv
파일/경로
open, with open, os, os.path.join, os.listdir, os.makedirs, pathlib.Path
open, with open, os, os.path.join, os.listdir, os.makedirs, pathlib.Path
직렬화
json.dumps, json.loads, json.dump, json.load, csv
json.dumps, json.loads, json.dump, json.load, csv
시간/로그
datetime.now, strftime, time, logging
datetime.now, strftime, time, logging
실행/압축/스크립트
argparse, subprocess.run, shutil.copy, glob.glob, tempfile, zipfile.ZipFile
argparse, subprocess.run, shutil.copy, glob.glob, tempfile, zipfile.ZipFile
네트워크/자동화
urllib, urllib.request, urllib.parse, webbrowser
urllib, urllib.request, urllib.parse, webbrowser
파일·경로·직렬화 코드 예시
import os
from pathlib import Path
import json
os.makedirs("data", exist_ok=True)
print(os.listdir("."))
path_str = os.path.join("data", "sample.json")
path = Path(path_str)
payload = {"name": "민수", "score": 95}
text = json.dumps(payload, ensure_ascii=False)
restored_text = json.loads(text)
with open(path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False)
with open(path, "r", encoding="utf-8") as f:
restored_file = json.load(f)
print(restored_text["name"], restored_file["score"])
실전에서는 json.dumps / json.loads처럼 문자열을 다루는 방식과 json.dump / json.load처럼 파일 객체를 다루는 방식을 구분해야 합니다. 경로 처리도 os.path.join()처럼 문자열 기반 조합과 pathlib.Path 기반 조합을 비교해 이해하면 훨씬 실전적입니다.
입력 인자·시간·네트워크·실행 예시
import sys, time, logging, argparse, subprocess, webbrowser
from urllib.parse import quote
from urllib.request import urlopen
from datetime import datetime
logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(message)s")
parser = argparse.ArgumentParser()
parser.add_argument("--name", default="python")
args = parser.parse_args([])
start = time.time()
now = datetime.now()
logging.info(now.strftime("%Y-%m-%d %H:%M:%S"))
print(sys.argv)
keyword = quote(args.name)
url = f"https://example.com/search?q={keyword}"
print(url)
result = subprocess.run(["echo", "hello"], capture_output=True, text=True)
print(result.stdout.strip())
# response = urlopen(url)
# webbrowser.open("https://www.python.org")
print(round(time.time() - start, 4))
argparse는 명령행 인자를 구조적으로 받고, logging은 진행 상황을 남기며, subprocess.run()은 외부 명령 실행에 씁니다. 여기서는 문서 예시를 안정적으로 보여 주기 위해 parse_args([])를 사용했지만, 실제 터미널 실행에서는 사용자가 입력한 인자를 그대로 받습니다. 시간 출력은 datetime.now().strftime()로 보기 좋게 다듬는 습관이 유용합니다. 네트워크 기초는 urllib.request와 urllib.parse, 간단한 자동화는 webbrowser에서 시작할 수 있습니다. 예시에서 urlopen()과 webbrowser.open()을 주석 처리한 이유는, 문서만 읽는 상황에서 의도치 않은 실제 요청이나 브라우저 실행을 막기 위해서입니다.
자동화·압축·임시파일 보강 예시
import glob, shutil, tempfile, zipfile
from pathlib import Path
json_files = glob.glob("data/*.json")
print(json_files)
if json_files:
shutil.copy(json_files[0], "backup_sample.json")
with tempfile.TemporaryDirectory() as tmpdir:
temp_path = Path(tmpdir) / "note.txt"
temp_path.write_text("hello", encoding="utf-8")
print(temp_path.exists())
with zipfile.ZipFile("sample.zip", "w") as zf:
if Path("backup_sample.json").exists():
zf.write("backup_sample.json")
glob.glob()은 패턴으로 파일을 찾고, shutil.copy()는 파일 복사, tempfile은 안전한 임시 작업 공간, zipfile.ZipFile은 압축 파일 생성과 해제에 사용합니다. 실전 자동화에서는 이런 조합이 자주 반복됩니다.
핵심 문법·패턴: map, filter, lambda, generator, comprehension
map / filter / lambda
데이터 변환과 조건 추출을 짧게 처리
데이터 변환과 조건 추출을 짧게 처리
comprehension 확장
리스트, 딕셔너리, 집합 표현식으로 재구성
리스트, 딕셔너리, 집합 표현식으로 재구성
generator
한 번에 다 만들지 않고 하나씩 생성
한 번에 다 만들지 않고 하나씩 생성
iterator와 generator 관계
generator는 iterator를 만드는 편리한 방법
generator는 iterator를 만드는 편리한 방법
nums = [1, 2, 3, 4, 5]
print(list(map(lambda x: x * 2, nums)))
print(list(filter(lambda x: x % 2 == 0, nums)))
print([x * 2 for x in nums if x % 2 == 0])
print({x: x * x for x in nums})
print({x for x in nums if x % 2 == 1})
def gen():
for i in range(3):
yield i
print(list(gen()))
초보자 필수 개념
- mutable / immutable : 문자열은 immutable, 리스트/딕셔너리/집합은 mutable
- truthy / falsy : 빈 문자열, 빈 리스트, 0, None은 조건문에서 거짓처럼 동작
- 형변환 : input은 문자열이므로 int, float, str 변환이 중요
- in / not in : 포함 검사와 멤버십 판단의 기본
- 자료형 선택 : 문자열 / 리스트 / 딕셔너리 / 집합은 목적이 다름
print(bool(""), bool([]), bool(0), bool(None))
print(bool("hi"), bool([1]), bool(7))
예외처리와 with의 의미
예외는 단순히 “실패했다”가 아니라, 프로그램이 예상하지 못한 상황을 만났다는 신호입니다. 실전 코드는 오류를 아예 없애는 것보다 왜 실패할 수 있는지 알고 안전하게 처리하는 것이 더 중요합니다.
try:
value = int("hello")
except ValueError:
print("숫자로 바꿀 수 없습니다")
finally:
print("예외 처리 종료")
with open("sample.txt", "w", encoding="utf-8") as f:
f.write("hello")
여기서 with는 context manager를 사용해 자원을 안전하게 열고 닫게 도와줍니다.
외부 라이브러리 보너스: Faker, pip, venv
표준 라이브러리만으로도 많은 일을 할 수 있지만, 실제 프로젝트에서는 외부 라이브러리를 설치해서 쓰는 경우가 많습니다. 이때 기본 개념이 되는 것이 pip와 venv입니다. pip는 패키지 설치 도구, venv는 프로젝트별 가상환경 분리 도구입니다.
# 설치 예시
# pip install faker
from faker import Faker
fake = Faker("ko_KR")
print(fake.name())
print(fake.email())
Faker는 가짜 이름, 주소, 이메일 같은 테스트 데이터를 빠르게 만들 때 유용합니다. 학습용으로도 좋고, 작은 프로젝트의 더미 데이터 생성에도 잘 맞습니다.
이 외전의 핵심 요약
문자열에서는 split, splitlines, partition, replace, strip, upper/lower, isalpha 계열, zfill, format, f-string이 핵심입니다.
리스트·튜플에서는 append, pop, sorted, reverse, copy, del, 음수 인덱싱, in/not in, 얕은 복사와 깊은 복사가 중요합니다.
딕셔너리·집합에서는 get, items, pop, update, copy, dict comprehension, set 연산, symmetric_difference, issubset/issuperset을 함께 봐야 합니다.
내장 함수는 input, print, int, float, str, len, range, enumerate, zip, map, filter, all, any, isinstance, type까지 연결해서 익히는 것이 좋습니다.
알고리즘 입문은 Counter, deque, heapq, bisect, itertools, math가 뼈대이고, 실전에서는 open, json.dump/load, os.path.join, pathlib.Path, logging, argparse, subprocess, glob, tempfile, zipfile, urllib, webbrowser까지 범위가 넓어집니다.
도구 목록보다 더 중요한 것은 mutable/immutable, truthy/falsy, context manager, 예외처리, iterator/generator 관계를 이해하는 것입니다.
체크리스트
□ 문자열은 immutable이라는 점과 문자열 메서드가 새 값을 반환한다는 점을 설명할 수 있다.
□ 리스트 복사에서 얕은 복사와 깊은 복사의 차이를 이해했다.
□ input → int/float/str 변환 → 처리 → print 흐름을 직접 설명할 수 있다.
□ Counter, deque, heapq, bisect, itertools, math.log, math.exp, math.isqrt가 어떤 상황에서 쓰일지 감이 온다.
□ open, with, json.dump/load, sys.argv, logging, argparse, subprocess.run, glob.glob, tempfile, zipfile, urllib.request, webbrowser의 쓰임새를 한 문장으로 설명할 수 있다.
미니 연습문제
- 문자열 두 줄을 가진 텍스트를 splitlines()로 분리해 보세요.
- 문자열을 partition()으로 세 부분으로 나누어 보세요.
- 숫자 문자열을 float()로 바꾼 뒤 소수 둘째 자리까지 출력해 보세요.
- 디렉터리를 os.makedirs()로 만들고, os.listdir()로 목록을 확인해 보세요.
- 숫자 하나를 정해 math.log()와 math.exp() 결과를 확인해 보세요.
- logging으로 시작/종료 메시지를 남기고, subprocess.run(["echo", "hello"]) 결과를 출력해 보세요.
- glob.glob()으로 특정 폴더의 파일 목록을 찾고, 그중 하나를 zipfile.ZipFile로 압축해 보세요.
Next Direction
이 외전은 파이썬 기초를 끝낸 뒤, 실전에서 자주 쓰는 메서드·함수·라이브러리·핵심 개념을 한 번에 정리하기 위한 보충편입니다.
문자열, 자료구조, 내장 함수, 알고리즘 도구, 파일 처리와 자동화 기초까지 이 흐름을 자기 것으로 만들면, 이후 자료구조와 함께 배우는 알고리즘 입문 파이썬편으로 훨씬 자연스럽게 이어질 수 있습니다.
'학습 자료 글 > 파이썬 시작하기' 카테고리의 다른 글
| [파이썬 기초 시리즈 12]정규표현식과 실전 응용 기초편 (0) | 2026.03.24 |
|---|---|
| [파이썬 기초 시리즈 11]예외 처리와 모듈 기초편 (0) | 2026.03.24 |
| [파이썬 기초 시리즈 10]파일 처리 기초편 (0) | 2026.03.24 |
| [파이썬 기초 시리즈 9]입력과 출력 기초편 (1) | 2026.03.24 |
| [파이썬 기초 시리즈 8]함수 기초편 (0) | 2026.03.23 |