List Comprehensions
One of Python's most "Pythonic" features is the list comprehension. It's a way of creating a list in a compact and, once you get used to them, readable way. See the demonstrations below.
The preferred 'pythonic' way to create a list
The above is equivalent to the following just more compact:
You can also choose to do computation / flow control when generating lists
This example uses the "modulo" operator
Advanced List Comprehensions [optional]
If you're already an advanced programmer, you may be interested in some of these more advanced list comprehensions. They're one of the things that experienced Python users learn to love about Python.
This example also uses a data type called a namedtuple which is similar to a struct
data type in other languages.
now let's show what we can do with a list comprehension
Create a list of names where there age
Last updated
Was this helpful?