# List Comprehensions and Built-In Functions on Lists

In this lesson, you’ll learn how to use list comprehensions to construct various lists, and different list methods to manipulate lists.

List comprehensions are a useful way to construct lists on the fly. They use the following syntax:

``````[<expr> for <elem> in <lst> if <cond>]
``````

Here’s an example:

>>>
``````>>> [(lambda x: x *x )(x) for x in [1, 2, -5, 4]]
[1, 4, 25, 16]
``````

They’re used in place of functions like `map()` and `filter()`. To learn more, check out Using List Comprehensions Effectively.

There are also some useful built-in functions that can be applied to lists such as `max()`, `min()`, `any()`, and `all()`:

• `max()` finds the maximum value of an iterable using the built-in `cmp()` method, or the `key` param.
• `min()` finds the minimum value of an iterable using the built-in `cmp()` method, or the `key` param.
• `any()` returns whether any of the elements in the iterable are a `true` value.
• `all()` returns whether all of the elements in the iterable are `true` values. Piotr

I wonder what’s the benefit of using

``````[(lambda x: x % 2 == 1)(num) for num in l]
``````

over simply

``````[bool(num % 2) for num in l]
``````

? James Uejio RP Team

@Piotr Good point! Either is fine in my opinion, bool() will assume that the user knows that 0 is a False value in Python (some languages it might be a True value), while lambda is more explicit. MichaelKareev

Probably it’s even more Pythonic for squaring list’s elements:

``````[x**2 for x in lst]
`````` sanketkamat10

Using the following code as well gets the same result instead of using lambda:

``````any([i % 2 == 1 for i in lst])
`````` Bartosz Zaczyński RP Team

@sanketkamat10 As long as you’re only interested in a simple yes-no answer, then you can simplify your example even further by dropping the square brackets:

``````any(i % 2 == 1 for i in lst)
``````

Such syntax declares a generator expression instead of a list comprehension. Rinkalaone

In case of using a boolean function with the built-in filter as in :

``````def is_odd(x):
return x % 2 == 1

lst = [1, -2, 9]
oddlist = list(filter(is_odd, lst))
``````

I wonder if there is a way to pass the boolean inverse of that function to the built-in filter? Something like:

``````evenlist = list(filter(not(is_odd), lst))
``````

…which is bringing the error “bool is not callable”.

Thanks James! Great course. Bartosz Zaczyński RP Team

@Rinkalaone You could try using a decorator like this:

``````>>> def is_odd(x):
...     return x % 2 == 1

>>> def not_(predicate):
...     def wrapper(x):
...         return not predicate(x)
...     return wrapper

>>> numbers = [1, -2, 9]

>>> list(filter(is_odd, numbers))
[1, 9]

>>> list(filter(not_(is_odd), numbers))
[-2]
`````` Rinkalaone

Awesome! Thank you Bartosz.

to join the conversation.