Python filter() 실전예제 20개

기초 필터링부터 문자열, 숫자, 딕셔너리, 사용자 정의 함수, map과의 조합까지 단계적으로 익히는 실습 자료

핵심 개념
filter(함수, 반복가능객체) 는 함수의 결과가 True인 요소만 골라내는 도구입니다.

1. 짝수만 걸러내기

코드

nums = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda x: x % 2 == 0, nums))
print(result)

설명

리스트에서 짝수만 남기는 가장 기본적인 filter 예제입니다.

실행 결과

[2, 4, 6]

2. 홀수만 걸러내기

코드

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

설명

조건식이 참인 값만 통과하므로 홀수만 추출할 수도 있습니다.

실행 결과

[1, 3, 5]

3. 10보다 큰 수만 추출

코드

nums = [3, 12, 7, 25, 1, 18]
result = list(filter(lambda x: x > 10, nums))
print(result)

설명

크기 비교 조건을 이용하여 원하는 범위의 값만 남길 수 있습니다.

실행 결과

[12, 25, 18]

4. 음수만 추출

코드

nums = [-5, 3, -2, 8, -1, 0]
result = list(filter(lambda x: x < 0, nums))
print(result)

설명

0보다 작은 값만 걸러내어 음수 목록을 만듭니다.

실행 결과

[-5, -2, -1]

5. 문자열 길이가 3 이상인 것만 추출

코드

words = ['hi', 'cat', 'a', 'python', 'go']
result = list(filter(lambda x: len(x) >= 3, words))
print(result)

설명

문자열 길이를 기준으로 필요한 단어만 선택할 수 있습니다.

실행 결과

['cat', 'python']

6. 빈 문자열 제거

코드

words = ['apple', '', 'banana', '', 'grape']
result = list(filter(None, words))
print(result)

설명

filter(None, iterable)은 참으로 평가되는 값만 남깁니다. 빈 문자열은 제거됩니다.

실행 결과

['apple', 'banana', 'grape']

7. 0 제거

코드

nums = [0, 1, 2, 0, 3, 0, 4]
result = list(filter(None, nums))
print(result)

설명

숫자 0은 거짓(False)으로 평가되므로 자동으로 제거됩니다.

실행 결과

[1, 2, 3, 4]

8. None 값 제거

코드

data = [10, None, 20, None, 30]
result = list(filter(lambda x: x is not None, data))
print(result)

설명

None 여부를 직접 검사해서 유효한 데이터만 남기는 예제입니다.

실행 결과

[10, 20, 30]

9. 대문자로 시작하는 단어만 추출

코드

words = ['Apple', 'banana', 'Cherry', 'dog']
result = list(filter(lambda x: x[0].isupper(), words))
print(result)

설명

문자열의 첫 글자를 검사하여 조건에 맞는 단어만 걸러냅니다.

실행 결과

['Apple', 'Cherry']

10. 모음으로 시작하는 단어만 추출

코드

words = ['apple', 'banana', 'orange', 'grape', 'egg']
result = list(filter(lambda x: x[0].lower() in 'aeiou', words))
print(result)

설명

문자 포함 여부를 조건으로 활용한 예제입니다.

실행 결과

['apple', 'orange', 'egg']

11. 3의 배수만 추출

코드

nums = list(range(1, 21))
result = list(filter(lambda x: x % 3 == 0, nums))
print(result)

설명

range와 함께 사용하면 규칙에 맞는 수만 쉽게 고를 수 있습니다.

실행 결과

[3, 6, 9, 12, 15, 18]

12. 합격자만 추출

코드

scores = [45, 82, 67, 90, 39]
result = list(filter(lambda x: x >= 60, scores))
print(result)

설명

점수 리스트에서 기준 점수 이상인 값만 남기는 전형적인 활용입니다.

실행 결과

[82, 67, 90]

13. 딕셔너리 리스트에서 성인만 추출

코드

people = [
    {'name': '민수', 'age': 17},
    {'name': '지우', 'age': 22},
    {'name': '서연', 'age': 19}
]
result = list(filter(lambda x: x['age'] >= 19, people))
print(result)

설명

딕셔너리 안의 특정 키 값을 기준으로 객체를 걸러낼 수 있습니다.

실행 결과

[{'name': '지우', 'age': 22}, {'name': '서연', 'age': 19}]

14. 파일 확장자가 .py인 것만 추출

코드

files = ['main.py', 'note.txt', 'app.py', 'image.png']
result = list(filter(lambda x: x.endswith('.py'), files))
print(result)

설명

문자열 메서드와 결합하면 실무형 필터링이 가능합니다.

실행 결과

['main.py', 'app.py']

15. 공백 제거 후 빈 값이 아닌 문자열만 추출

코드

texts = ['apple', '   ', 'banana', '', ' grape ']
result = list(filter(lambda x: x.strip() != '', texts))
print(result)

설명

strip()을 활용해 공백만 있는 문자열도 걸러낼 수 있습니다.

실행 결과

['apple', 'banana', ' grape ']

16. 특정 문자 포함 단어만 추출

코드

words = ['star', 'sun', 'sky', 'stone', 'moon']
result = list(filter(lambda x: 's' in x, words))
print(result)

설명

문자 포함 여부를 이용해 필요한 단어만 추려냅니다.

실행 결과

['star', 'sun', 'sky', 'stone']

17. 사용자 정의 함수로 소수만 추출

코드

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

nums = list(range(1, 21))
result = list(filter(is_prime, nums))
print(result)

설명

filter에는 lambda뿐 아니라 일반 함수도 넣을 수 있습니다.

실행 결과

[2, 3, 5, 7, 11, 13, 17, 19]

18. filter 객체를 for문으로 직접 순회

코드

nums = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, nums)
for x in result:
    print(x, end=' ')

설명

filter는 iterator를 반환하므로 list로 바꾸지 않고 바로 순회할 수도 있습니다.

실행 결과

2 4 6

19. map과 filter 함께 사용

코드

nums = [1, 2, 3, 4, 5, 6]
result = list(map(lambda x: x * 10, filter(lambda x: x % 2 == 0, nums)))
print(result)

설명

먼저 filter로 짝수만 고른 뒤 map으로 값을 변환하는 조합 예제입니다.

실행 결과

[20, 40, 60]

20. filter와 리스트 컴프리헨션 비교

코드

nums = [1, 2, 3, 4, 5, 6]
a = list(filter(lambda x: x % 2 == 0, nums))
b = [x for x in nums if x % 2 == 0]
print(a)
print(b)

설명

filter와 리스트 컴프리헨션은 비슷한 결과를 만들 수 있습니다.

실행 결과

[2, 4, 6]
[2, 4, 6]