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-incmp()
method, or thekey
param.min()
finds the minimum value of an iterable using the built-incmp()
method, or thekey
param.any()
returns whether any of the elements in the iterable are atrue
value.all()
returns whether all of the elements in the iterable aretrue
values.
To learn more, check out Python Docs Built-in Functions.
Piotr on April 25, 2020
I wonder what’s the benefit of using
over simply
?