Stats

2131 Contributors: 20 Wednesday, June 21, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

List Comprehensions

Introduction

A list comprehension is a syntactical tool for creating lists in a natural and concise way, as illustrated in the following code to make a list of squares of the numbers 1 to 10: [i ** 2 for i in range(1,11)] The dummy i from an existing list range is used to make a new element pattern. It is used where a for loop would be necessary in less expressive languages.

Syntax

  • [i for i in range(10)] # basic list comprehension
  • [i for i in xrange(10)] # basic list comprehension with generator object in python 2.x
  • [i for i in range(20) if i % 2 == 0] # with filter
  • [x + y for x in [1, 2, 3] for y in [3, 4, 5]] # nested loops
  • [i if i > 6 else 0 for i in range(10)] # ternary expression
  • [i if i > 4 else 0 for i in range(20) if i % 2 == 0] # with filter and ternary expression
  • [[x + y for x in [1, 2, 3]] for y in [3, 4, 5]] # nested list comprehension

Remarks

List comprehensions were outlined in PEP 202 and introduced in Python 2.0.

Related Examples