Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Filtering List Comprehensions

Give Feedback

In this lesson, you’ll see that list comprehensions are often recommended by Python core developers as a more Pythonic solution than the filter() function you used in the previous lesson.

You can also skip the middle man and use a generator expression to get the same result but not create a list in the process. A generator expressions defines an ad hoc iterator that then produces values for you without first creating a list, and then creating a tuple from that list, and then destroying the list again, so it’s more memory efficient.

Comments & Discussion

espdave4 on April 3, 2020

For line:

print(tuple(x for x in scientists if x.nobel is True))
TypeError: 'tuple' object is not callable

Any reason why?

George Yeboah on April 4, 2020

u missed the the tuple parentenses like the this print(tuple((x for x in scientists if x.nobel is True)))

Anh Lu on April 20, 2020

So if tuple(filter(lambda x: x.nobel, scientist)) and tuple(x for x in scientist if x.nobel) return the same result, when should we use one over the other?

Dan Bader RP Team on April 20, 2020

Comprehensions are generally deemed as more Pythonic, so I’d go with this version:

tuple(x for x in scientist if x.nobel)

(Technically, you’re writing a generator expression in this case but syntactically they’re the same as list comprehensions.)

Become a Member to join the conversation.