Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Returning True or False instead of the list

Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [num % 2 == 0 for num in a]

print(b)

why does this only return "True" or "False" but not the numbers themselves?

1 Answer

You want to create b like this:

b = [num for num in a if num % 2 == 0]

This way it will iterate over the numbers in a and only add them to b if num % 2 == 0

Thank you. Can you elaborate the difference between this line and mine though?

The way you have it, it's iterating over a and just checking if each num % 2 == 0, and returning the boolean value. Think of its this way...

for num in a:
    return num % 2 == 0

where you can think of the way i wrote it as:

for num in a:
    if num % 2 == 0:
        b.append(num)
return b