A list comprehension in Python is a concise way to create lists by transforming elements from an existing iterable (like a list, range, or string) through a single line of code. It makes a new list by applying an expression to each item in the iterable, optionally filtering out items with a condition.

Basic Syntax

[expression for item in iterable if condition]
  • Expression: what you want to do for each item, like modify
  • Item: each element from the iterable
  • Iterable: the collection you’re looping through
  • Condition: optional, a filter that determines which items are included

Examples

When practicing Higher Order Functions, I discovered list comprehensions when trying to build my custom_map() function in line 4:

names = ['phin', 'jon', 'kaye']
 
def custom_map(func, values):
	return [func(value) for value in values]
 
capitalized_names = custom_map(str.capitalize, names)
 
print(list(capitalized_names))
% ['Phin', 'Jon', 'Kaye']