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
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
- The loop version starts with an empty list and appends
n * nfor everyn. - The comprehension
[n * n for n in numbers]does exactly the same in one line: the part beforeforis what goes into the new list. - An
ifat the end filters the items, so[n * n for n in numbers if n % 2 == 0]squares only the even numbers. - 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
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()
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.
Related programs
- Find the Sum of Squares of the First N Numbers
- Check if a Number Is a Perfect Square
- Separate Even and Odd Numbers in a List
- Calculate the Power of a Number
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises