리스트 컴프리헨션

Python 도구 상자

Hugo Bowne-Anderson

Data Scientist at DataCamp

for 루프로 리스트 채우기

nums = [12, 8, 21, 3, 16]

new_nums = []
for num in nums: new_nums.append(num + 1)
print(new_nums)
[13, 9, 22, 4, 17]
Python 도구 상자

리스트 컴프리헨션

nums = [12, 8, 21, 3, 16]
new_nums = [num + 1 for num in nums]

print(new_nums)
[13, 9, 22, 4, 17]
Python 도구 상자

for 루프 vs 리스트 컴프리헨션 문법

new_nums = [num + 1 for num in nums]
for num in nums:
    new_nums.append(num + 1)

print(new_nums)
[13, 9, 22, 4, 17]
Python 도구 상자

range()와 리스트 컴프리헨션

result = [num for num in range(11)]

print(result)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python 도구 상자

리스트 컴프리헨션

  • 리스트 생성용 for 루프를 한 줄로 축약
  • 구성 요소
    • 이터러블
    • 이터레이터 변수(이터러블의 원소 표시)
    • 출력 표현식
Python 도구 상자

중첩 루프 (1)

pairs_1 = []

for num1 in range(0, 2): for num2 in range(6, 8): pairs_1.append((num1, num2))
print(pairs_1)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • 이를 리스트 컴프리헨션으로 구현하려면?
Python 도구 상자

중첩 루프 (2)

pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2 in range(6, 8)]

print(pairs_2)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • 트레이드오프: 가독성
Python 도구 상자

연습해 봅시다!

Python 도구 상자

Preparing Video For Download...