Skip to Content
💻 코리아IT아카데미 신촌 - 프로그래밍 학습 자료

Topic 4: 람다 함수 - 간결한 익명 함수 ⚡

🎯 학습 목표

람다 함수의 개념과 특징을 이해하고, map(), filter(), sort() 등과 함께 사용하여 간결하고 효율적인 코드를 작성할 수 있습니다.

⚡ 람다 함수란?

일회용 함수의 필요성

일상생활에서 간단한 계산을 할 때를 생각해보세요:

  • 숫자에 2를 곱하기
  • 두 숫자 중 큰 값 찾기
  • 문자열이 특정 조건을 만족하는지 확인

이런 간단한 작업을 위해 복잡한 함수를 만들 필요가 있을까요?

# 일반 함수로 작성하면... def multiply_by_two(x): return x * 2 def is_even(x): return x % 2 == 0 # 이런 간단한 작업에도 여러 줄이 필요해요

람다 함수의 등장

람다 함수는 이름이 없는 익명 함수로, 간단한 연산을 한 줄로 표현할 수 있습니다.

# 람다 함수로 간결하게! multiply_by_two = lambda x: x * 2 is_even = lambda x: x % 2 == 0 print(multiply_by_two(5)) # 10 print(is_even(4)) # True

📝 람다 함수 문법

기본 구조

lambda 매개변수: 반환값

일반 함수 vs 람다 함수

# 일반 함수 def add(x, y): return x + y # 람다 함수 add = lambda x, y: x + y print(add(3, 5)) # 8 (결과는 동일)

다양한 람다 함수 예시

# 매개변수가 하나인 람다 square = lambda x: x ** 2 print(square(4)) # 16 # 매개변수가 여러 개인 람다 multiply = lambda x, y: x * y print(multiply(3, 4)) # 12 # 조건문이 있는 람다 max_value = lambda x, y: x if x > y else y print(max_value(10, 20)) # 20 # 문자열 처리 람다 capitalize_first = lambda text: text[0].upper() + text[1:].lower() print(capitalize_first("hello")) # Hello

🗺️ map() 함수와 람다

map() 함수의 역할

map() 함수는 리스트의 모든 요소에 함수를 적용해서 새로운 리스트를 만듭니다.

# 기본 구조 map(함수, 리스트)

람다와 map() 조합

# 모든 숫자에 2를 곱하기 numbers = [1, 2, 3, 4, 5] # 일반 함수 사용 def multiply_by_two(x): return x * 2 result1 = list(map(multiply_by_two, numbers)) print(result1) # [2, 4, 6, 8, 10] # 람다 함수 사용 (더 간결!) result2 = list(map(lambda x: x * 2, numbers)) print(result2) # [2, 4, 6, 8, 10]

실용적인 map() 활용

# 문자열 리스트를 대문자로 변환 names = ["김철수", "이영희", "박민수"] upper_names = list(map(lambda name: name.upper(), names)) print(upper_names) # ['김철수', '이영희', '박민수'] # 숫자 문자열을 정수로 변환 str_numbers = ["1", "2", "3", "4", "5"] int_numbers = list(map(lambda x: int(x), str_numbers)) print(int_numbers) # [1, 2, 3, 4, 5] # 간단한 계산식 적용 prices = [1000, 2000, 3000, 4000] discounted = list(map(lambda price: price * 0.9, prices)) print(discounted) # [900.0, 1800.0, 2700.0, 3600.0]

🔍 filter() 함수와 람다

filter() 함수의 역할

filter() 함수는 조건을 만족하는 요소만 골라내서 새로운 리스트를 만듭니다.

# 기본 구조 filter(조건함수, 리스트)

람다와 filter() 조합

# 짝수만 필터링 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 일반 함수 사용 def is_even(x): return x % 2 == 0 even_numbers1 = list(filter(is_even, numbers)) print(even_numbers1) # [2, 4, 6, 8, 10] # 람다 함수 사용 (더 간결!) even_numbers2 = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers2) # [2, 4, 6, 8, 10]

실용적인 filter() 활용

# 특정 점수 이상만 필터링 scores = [85, 92, 78, 96, 83, 91, 74, 88] high_scores = list(filter(lambda score: score >= 90, scores)) print(high_scores) # [92, 96, 91] # 특정 길이 이상의 단어만 필터링 words = ["안녕", "파이썬", "프로그래밍", "코딩", "개발"] long_words = list(filter(lambda word: len(word) >= 3, words)) print(long_words) # ['파이썬', '프로그래밍'] # 양수만 필터링 mixed_numbers = [-5, -2, 0, 3, 7, -1, 9] positive = list(filter(lambda x: x > 0, mixed_numbers)) print(positive) # [3, 7, 9]

📊 sorted() 함수와 람다

sorted() 함수의 key 매개변수

sorted() 함수에서 key 매개변수로 정렬 기준을 지정할 수 있습니다.

# 기본 구조 sorted(리스트, key=정렬기준함수)

람다와 sorted() 조합

# 학생 정보 리스트 students = [ ("김철수", 85), ("이영희", 92), ("박민수", 78), ("최지영", 96) ] # 점수를 기준으로 정렬 sorted_by_score = sorted(students, key=lambda student: student[1]) print(sorted_by_score) # [('박민수', 78), ('김철수', 85), ('이영희', 92), ('최지영', 96)] # 점수를 기준으로 내림차순 정렬 sorted_desc = sorted(students, key=lambda student: student[1], reverse=True) print(sorted_desc) # [('최지영', 96), ('이영희', 92), ('김철수', 85), ('박민수', 78)]

다양한 정렬 기준

# 문자열 길이로 정렬 words = ["파이썬", "프로그래밍", "코딩", "개발", "알고리즘"] sorted_by_length = sorted(words, key=lambda word: len(word)) print(sorted_by_length) # ['코딩', '개발', '파이썬', '알고리즘', '프로그래밍'] # 절댓값으로 정렬 numbers = [-5, 3, -1, 8, -2, 6] sorted_by_abs = sorted(numbers, key=lambda x: abs(x)) print(sorted_by_abs) # [-1, -2, 3, -5, 6, 8] # 딕셔너리 리스트 정렬 products = [ {"name": "노트북", "price": 1200000}, {"name": "마우스", "price": 30000}, {"name": "키보드", "price": 80000} ] sorted_by_price = sorted(products, key=lambda product: product["price"]) print(sorted_by_price) # [{'name': '마우스', 'price': 30000}, {'name': '키보드', 'price': 80000}, {'name': '노트북', 'price': 1200000}]

🔄 람다 함수의 활용 패턴

리스트 컴프리헨션 vs 람다

numbers = [1, 2, 3, 4, 5] # 리스트 컴프리헨션 squares1 = [x ** 2 for x in numbers] # 람다와 map squares2 = list(map(lambda x: x ** 2, numbers)) print(squares1) # [1, 4, 9, 16, 25] print(squares2) # [1, 4, 9, 16, 25] (결과 동일)

조건부 람다

# 조건에 따른 다른 처리 numbers = [1, 2, 3, 4, 5, 6] # 짝수는 2로 나누고, 홀수는 2를 곱하기 result = list(map(lambda x: x // 2 if x % 2 == 0 else x * 2, numbers)) print(result) # [2, 1, 6, 2, 10, 3]

📊 실용적인 활용 예시

예시 1: 데이터 전처리

# 사용자 입력 데이터 정리 user_inputs = [" Apple ", " BANANA ", "orange", " GRAPE "] # 공백 제거하고 첫 글자만 대문자로 cleaned = list(map(lambda text: text.strip().capitalize(), user_inputs)) print(cleaned) # ['Apple', 'Banana', 'Orange', 'Grape']

예시 2: 성적 등급 계산

# 점수를 등급으로 변환 scores = [95, 87, 92, 78, 85, 91, 73, 88] # 점수에 따른 등급 부여 grades = list(map(lambda score: 'A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'D', scores)) print("점수:", scores) print("등급:", grades) # 점수: [95, 87, 92, 78, 85, 91, 73, 88] # 등급: ['A', 'B', 'A', 'C', 'B', 'A', 'C', 'B']

예시 3: 온라인 쇼핑몰 상품 필터링

# 상품 데이터 products = [ {"name": "노트북", "price": 1200000, "category": "전자기기"}, {"name": "티셔츠", "price": 25000, "category": "의류"}, {"name": "스마트폰", "price": 800000, "category": "전자기기"}, {"name": "청바지", "price": 45000, "category": "의류"}, {"name": "헤드폰", "price": 150000, "category": "전자기기"} ] # 50만원 이하 전자기기 필터링 affordable_electronics = list(filter( lambda product: product["category"] == "전자기기" and product["price"] <= 500000, products )) print("50만원 이하 전자기기:") for product in affordable_electronics: print(f"- {product['name']}: {product['price']:,}원") # - 헤드폰: 150,000원 # 가격순으로 정렬 sorted_products = sorted(products, key=lambda product: product["price"]) print("\n가격순 정렬:") for product in sorted_products: print(f"- {product['name']}: {product['price']:,}원")

⚖️ 람다 vs 일반 함수

언제 람다를 사용할까?

람다 함수 사용이 좋은 경우:

  • 간단한 한 줄 연산
  • map(), filter(), sorted() 등과 함께 사용
  • 일회성 함수

일반 함수 사용이 좋은 경우:

  • 복잡한 로직
  • 여러 줄의 코드
  • 재사용이 많은 함수
  • 디버깅이 필요한 경우
# 👍 람다가 적합한 경우 numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x ** 2, numbers)) # 👍 일반 함수가 적합한 경우 def complex_calculation(x): """복잡한 계산을 수행하는 함수""" if x < 0: return 0 elif x < 10: return x * 2 else: result = x ** 2 result = result + x return result % 100 processed = [complex_calculation(x) for x in numbers]

🚧 람다 함수의 제한사항

람다의 한계

# ❌ 람다에서 할 수 없는 것들 # 1. 여러 줄 코드 # lambda x: print(x) # 문(statement)은 사용 불가 # return x * 2 # 2. 변수 할당 # lambda x: y = x * 2 # 변수 할당 불가 # 3. 복잡한 제어문 # lambda x: if x > 0: # 복잡한 if문 불가 # return x # else: # return -x # ✅ 람다로 가능한 것들 simple_condition = lambda x: x if x > 0 else -x # 삼항 연산자는 가능

가독성 고려

# 🤔 너무 복잡한 람다 (비추천) complex_lambda = lambda x: x ** 2 + 3 * x - 5 if x > 10 else x * 2 if x > 5 else x + 1 # 😊 일반 함수로 명확하게 (추천) def process_number(x): """숫자를 조건에 따라 처리하는 함수""" if x > 10: return x ** 2 + 3 * x - 5 elif x > 5: return x * 2 else: return x + 1

🚨 자주 발생하는 오류

오류 1: 람다에서 print() 사용

# ❌ 틀린 예 numbers = [1, 2, 3] # list(map(lambda x: print(x), numbers)) # TypeError # ✅ 올바른 예 numbers = [1, 2, 3] for num in numbers: print(num) # 또는 def print_and_return(x): print(x) return x list(map(print_and_return, numbers))

오류 2: 변수 범위 문제

# ❌ 주의해야 할 예 multiplier = 10 functions = [] for i in range(3): # 모든 람다가 마지막 i 값을 참조 functions.append(lambda x: x * i) # 예상과 다른 결과 for f in functions: print(f(5)) # 모두 10 출력 (0, 5, 10이 아님) # ✅ 올바른 예 multiplier = 10 functions = [] for i in range(3): # 기본 매개변수로 i 값을 고정 functions.append(lambda x, mult=i: x * mult) for f in functions: print(f(5)) # 0, 5, 10 출력

💡 퀴즈: 람다 함수 이해도 체크

Q1. 다음 람다 함수의 결과는?

add_ten = lambda x: x + 10 result = add_ten(5) print(result)
  1. 5
  2. 10
  3. 15
  4. 오류 발생

💡 정답 확인

정답: 3번 (15)

람다 함수 add_ten은 입력값에 10을 더해서 반환합니다.

Q2. 다음 코드의 출력 결과는?

numbers = [1, 2, 3, 4, 5] result = list(filter(lambda x: x % 2 == 1, numbers)) print(result)
  1. [1, 3, 5]
  2. [2, 4]
  3. [1, 2, 3, 4, 5]
  4. []

💡 정답 확인

정답: 1번 ([1, 3, 5])

filter() 함수는 조건을 만족하는 요소만 반환하며, x % 2 == 1은 홀수 조건입니다.

Q3. 다음 코드의 출력 결과는?

words = ["apple", "banana", "cherry"] result = list(map(lambda word: len(word), words)) print(result)
  1. [“apple”, “banana”, “cherry”]
  2. [5, 6, 6]
  3. [a, b, c]
  4. 오류 발생

💡 정답 확인

정답: 2번 ([5, 6, 6])

map() 함수가 각 단어의 길이를 계산해서 새로운 리스트를 만듭니다.

✅ 람다 함수 마스터 체크리스트

✅ 람다 함수 마스터 체크리스트

🎉 Unit 5 Topic 4 완성!

람다 함수를 학습하면서 함수형 프로그래밍의 기초를 익혔습니다!

🏆 이번 토픽에서 배운 내용

  1. 람다 기본: 익명 함수의 개념과 문법
  2. map() 활용: 모든 요소에 함수 적용하기
  3. filter() 활용: 조건에 맞는 요소만 선택하기
  4. sorted() 활용: 사용자 정의 기준으로 정렬하기
  5. 실용적 패턴: 데이터 처리와 변환 기법

🚀 이제 할 수 있는 것들

  • 간단한 함수를 한 줄로 간결하게 표현
  • 리스트 데이터를 효율적으로 변환하고 필터링
  • 복잡한 정렬 기준을 쉽게 구현
  • 함수형 프로그래밍 패러다임의 기초 활용
  • 코드를 더 간결하고 읽기 쉽게 작성

람다 함수는 파이썬 프로그래밍에서 코드를 간결하고 효율적으로 만드는 강력한 도구입니다. 적절히 활용하면 더욱 우아하고 읽기 쉬운 코드를 작성할 수 있습니다! 🚀

Last updated on