List Comprehensions
Explore list comprehensions to create lists in Python from other iterables with clear and concise syntax. Understand their advantages over loops and map functions, and learn to apply conditions and nested structures to efficiently generate lists.
We'll cover the following...
It is often useful to create a list with particular content, perhaps based on another list or iterable. It is possible to do this using a loop, or, perhaps, a map function.
List comprehensions provide an alternative that is more declarative than a loop and often clearer than using a map function.
In addition to list comprehensions, there are similar techniques for generating lazy iterators (generator comprehensions), sets, and dictionaries, which we will also cover in this chapter.
List comprehension examples
To start with a simple example, suppose we want to create a list of length 100, filled with the strings, '0’ to ‘99’. There are several ways to do this. Firstly, we could ...