List Comprehension
List comprehensions are used to derive a new list from an existing list. It's a short way to write one or multiple for loops.
A list comprehension consists of
an input sequence
an expression that yields the elements of the derived list
an iterator over the input sequence
a logical condition over the iterator (optional)
List comprehension can support multiple levels of looping. But it's best practice to avoid more than two nested comprehensions and use conventional nested for loops.
List comprehension also works on set.
Last updated