Editor

Python Program to Make a List of Squares Using List Comprehension

Beginner · Lists

A list comprehension builds a new list from an old one in a single line, in the form [expression for item in list]. This program makes a list of squares first with an ordinary loop and then with a list comprehension, so you can compare the two, and adds a condition to keep only some items.

Program

squares_with_list_comprehension.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# The loop way
squares_loop = []
for n in numbers:
squares_loop.append(n * n)
# The list comprehension way: [expression for item in list]
squares = [n * n for n in numbers]
print("Numbers:", numbers)
print("Squares using a loop:", squares_loop)
print("Squares using a list comprehension:", squares)
# With a condition: squares of the even numbers only
even_squares = [n * n for n in numbers if n % 2 == 0]
print("Squares of the even numbers:", even_squares)
Output
Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Squares using a loop: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Squares using a list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Squares of the even numbers: [4, 16, 36, 64, 100]

How it works

  1. The loop version starts with an empty list and appends n * n for every n.
  2. The comprehension [n * n for n in numbers] does exactly the same in one line: the part before for is what goes into the new list.
  3. An if at the end filters the items, so [n * n for n in numbers if n % 2 == 0] squares only the even numbers.
  4. Both versions give the same list, and the comprehension is the style most Python programmers use for simple cases like this.

Other ways to write it

With range() and a dictionary comprehension

With range() and a dictionary comprehension
squares = [n ** 2 for n in range(1, 11)]
print("Squares of 1 to 10:", squares)
cubes = [n ** 3 for n in range(1, 6)]
print("Cubes of 1 to 5:", cubes)
square_of = {n: n ** 2 for n in range(1, 6)}
print("As a dictionary:", square_of)
Output
Squares of 1 to 10: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Cubes of 1 to 5: [1, 8, 27, 64, 125]
As a dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

range() supplies the numbers directly, ** raises to a power, and curly brackets with key: value make a dictionary comprehension instead.

Using map()

Using map()
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda n: n * n, numbers))
print("Squares using map():", squares)
Output
Squares using map(): [1, 4, 9, 16, 25]

map() applies a function to every item. It is an older style, and most people find the list comprehension easier to read.

Try it yourself

Write a list comprehension that gives the squares of the odd numbers from 1 to 15.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises