1 min read

Python List Comprehensions

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Syntax

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Examples

Basic Iteration

Instead of using a for loop:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)

You can do this in one line:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]

print(newlist)

Condition

The condition is like a filter that only accepts the items that valuate to True.

newlist = [x for x in fruits if x != "apple"]

Expression

The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list:

newlist = [x.upper() for x in fruits]

programming/python/python