List Comprehensions

Create a List of Squares

How would I create a list of numbers that are the square root of 0 through 9?

""" don't just use the list literal """
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = []
for i in range(10):
	squares.append(i**2)

Create a List of Squares

How would I create a list of numbers that are the square root of 0 through 9, but only include squares that are divisible by 2?

""" don't just use the list literal """
[0, 4, 16, 36, 64]
squares = []
for i in range(10):
	if i % 2 == 0:
		squares.append(i**2)

Quick Summary

List Comprehensions

List comprehensions are another, more concise way of creating lists. A list comprehension is syntactic sugar (syntax within a programming language that is designed to make things easier to read or to express) for the code that we created previously.

List comprehensions make new lists

List Comprehension Syntax

Two Examples: Squares, and Squares Divisible by 2

[x * x for x in range(10)]
[x * x for x in range(10) if x % 2 == 0]

Another List Comprehension

Write a list comprehension that creates a new list by adding exclamation points to every element in an existing list.

items = ['foo', 'bar', 'baz', 'busy']
[s + '!' for s in items]

And Another List Comprehension!

Limit the previous list to strings of length 3.

"""
filter the list called items (below), so that the resulting list is:
['foo', 'bar', 'baz']
"""
items = ['foo', 'bar', 'baz', 'busy']
[s for s in items if len(s) == 3]