When would using the filter function be used instead of a list comprehension?

Viewed 308

Recently, I have learned a bit about the filter method, an alternative to using list comprehensions.

Say I have a list as such:

names = ["Bob", "Billy", "Samuel", "Adam", "Rob"]

Now, I would like to get a list containing the names that start with the letter, "B". I could go about this in a couple of ways. This is one:

b_starting_names = list(filter(lambda name: name.startswith("B"), names))

This is another:

b_starting_names = [name for name in names if name.startswith("B")]

Could someone please explain what the difference is between a list comprehension and the filter function, and why someone may want to use one over the other?

1 Answers

There's no harm in using either. A similar comment can be made about map.

I tend to use whatever one feels easier to read. In your case I would avoid using the lambda as it is a bit verbose, and instead use the comprehension.

I would use filter or map methods if I already had a function existing I could just pass to the method, which would be more terse than the comprehension.

For example, say I write a program for finding the length of the largest name:

# Using map
longest = max(map(len, names))

# Using generator expression
longest = max(len(name) for name in names))

In the above example I would choose map over the generator expression, but it's entirely personal preference.

Related