Search⌘ K

List Comprehension

Explore how to create new lists from existing ones in Python using list comprehension. Understand its syntax with expressions, loops, and optional conditions, and learn to apply it with multiple lists to write concise and readable code.

List comprehension is a technique that uses a for loop and optionally a condition to create a new list from an existing one. The result is always a new list, so it’s good practice to assign a list comprehension to a new variable.

Structure

A list comprehension statement is always enclosed in square brackets, []. The comprehension consists of three main parts:

  • The expression is an operation used to create elements in the new list.

  • The for loop will iterate an existing list. The iterator will be used in the expression.

  • New elements ...