How to use python's list comprehension?

List comprehensions provide a concise way to create lists in Python.

Example to create a list of squares:


  numbers = [1, 2, 3, 4, 5]
  squares = [x*x for x in numbers]
  

Solution:

A list comprehension consists of an expression followed by a for clause, and can have one or more if clauses. The resulting list will contain the values produced by the expression, evaluated for each item that meets the conditions.

Beginner's Guide to Python