Comprenhensions

Resources

List comprehensions

List comprehensions allow us to create lists by processing an iterable, item by item, in a concise way. Each element of the resulting list will result from applying an operation to a corresponding item of the original iterable.

Imagine that we want to create a list with the squares of the integers from 1 to 10. We could write a for loop that keeps on adding elements to a previously created list.

An alternative way of accomplishing the same task very concisely is to create a list comprehension.

So, comprehensions take elements from an iterable and do an operation on each element.

Moreover, we can even filter the elements. For instance, we could choose to generate only the squares from the odd integers.

Other comprehensions

Comprehensions are not limited to lists we can also create dictionaries.

Or sets:

Generator expressions

Finally, you can also create comprehensions that are lazily evaluated, they are generators expressions.

Be careful because generators are consumed when used.

Exercises

Given a list of words, create a list with the length of each word and the maximum length.

Tip

Uppercase every word in the list.

Tip

Uppercase only the words smaller than 5 characters in the list.

Tip

Tag integers as odd or even. You can use a list comprehension with the ternary operator.

Tip

Given a string, build a set comprehension with the vowels present.

Tip