List Comprehension (Python)

Wonbin Lee·2022년 3월 20일
0

Python

목록 보기
5/5

Comprehension이란 iterable한 오브젝트를 생성하기 위한 방법중 하나로 파이썬에서 사용할 수 있는 유용한 기능중 하나이다.

Python에는 여라가지 Comprehension이 있다. 나는 그 중 하나인 List Comprehension 을 다룰 것이다.

result =[]

for i in range(1, 21):
    if i % 2 == 0:
        result.append(i)  
    
print(result)

>>> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

20 이하의 짝수를 리스트에 담는 코드이다. 여기서 우리는 List Comprehension을 이용할 수 있다.

List Comprehension 이용

result = [i for i in range(1,21) if i % 2 ==0]

print(result)

>>> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

이렇게 List Comprehension을 이용하면 한줄만에 코드를 끝낼 수 있다.

profile
Developer who level up every day ✌️

0개의 댓글