Unit 6Comprehending Lists Through List Comprehension

List comprehension is an expression that transforms a collection (not necessarily a list) into a list. It is used to apply the same operation to all or some list elements, such as converting all elements to uppercase or raising them all to a power.

The transformation process looks like this:

  1. The expression iterates over the collection and visits the items from the collection.

  2. An optional Boolean expression (default True) is evaluated for each item.

  3. If the Boolean expression is True, the loop expression is evaluated for the current item, and its value is appended to the result list.

  4. If the Boolean expression is False, the item is ignored.

Here are some trivial list comprehensions:

 # Copy ...

Get Data Science Essentials in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.