# List comprehension

## Introduction

List comprehensions in Python are concise, syntactic constructs. They can be utilized to generate lists from other lists by applying functions to each element in the list. The following section explains and demonstrates the use of these expressions.

## Syntax

`[x + 1 for x in (1, 2, 3)]`

# list comprehension, gives [2, 3, 4]`(x + 1 for x in (1, 2, 3))`

# generator expression, will yield 2, then 3, then 4`[x for x in (1, 2, 3) if x % 2 == 0`

] # list comprehension with filter, gives [2]`[x + 1 if x % 2 == 0 else x for x in (1, 2, 3)`

] # list comprehension with ternary`[x + 1 if x % 2 == 0 else x for x in range(-3,4) if x > 0]`

# list comprehension with ternary and filtering`{x for x in (1, 2, 2, 3)}`

# set comprehension, gives {1, 2, 3}`{k: v for k, v in [(‘a’, 1), (‘b’, 2)]}`

# dict comprehension, gives {‘a’: 1, ‘b’: 2} (python 2.7+ and 3.0+ only)`[x + y for x in [1, 2] for y in [10, 20]]`

# Nested loops, gives [11, 21, 12, 22]- [
`x + y for x in [1, 2, 3] if x > 2 for y in [3, 4, 5]]`

# Condition checked at 1st for loop `[x + y for x in [1, 2, 3] for y in [3, 4, 5] if x > 2]`

# Condition checked at 2nd for loop`[x for x in xrange(10) if x % 2 == 0]`

# Condition checked if looped numbers are odd numbers

## Remarks

Comprehensions are syntactical constructs which define data structures or expressions unique to a particular language. Proper use of comprehensions reinterpret these into easily-understood expressions. As expressions, they can be used:

- in the right hand side of assignments
- as arguments to function calls
- in the body of a lambda function
- as standalone statements. (For example:
`[print(x) for x in range(10)]`

)

Found a mistake? Have a question or improvement idea?
Let me know.

Table Of Contents