Junior — Senior
Why does a TypeError occur when checking the length of the filter result
livecode
Task condition
Explain why a TypeError exception occurs in the given example and suggest ways to fix it.
nums = [1, 2, 3, 4, 5]
# Form a list of odd numbers from nums
odd_numbers = filter(lambda x: x % 2, nums)
print(len(odd_numbers) > 0) # TypeError
Reason: In Python 3, the filter function returns an iterator, not a list. Iterators do not have a __len__ method, so calling len() on it results in TypeError: object of type 'filter' has no len().
How to fix:
- Convert the result to a list:
odd_numbers = list(filter(lambda x: x % 2, nums)). - Or use a list comprehension:
odd_numbers = [x for x in nums if x % 2]. - If you only need to check if there is at least one odd element, you can use
any:print(any(x % 2 for x in nums)). All options fix the error, allowing you to correctly check if there are odd numbers in the original array.