Python Practice › List Programs › Program 1
Square of each number in a list
Write a Python program to calculate the square of each number in a list.
Input
[2, 4, 6, 8, 10]
Output
[4, 16, 36, 64, 100]
Approach
- Loop over the list and append each number squared, or use a list comprehension.
Solution 1: loop
numbers = [2, 4, 6, 8, 10]squares = []for n in numbers: squares.append(n ** 2)print(squares)Output
[4, 16, 36, 64, 100]
Line by line
Line 2
Start with an empty list for the results.
Lines 3-4
n ** 2 squares each number and append adds it to the end.
Solution 2: list comprehension
numbers = [2, 4, 6, 8, 10]print([n ** 2 for n in numbers])Output
[4, 16, 36, 64, 100]
Line by line
Line 2
The comprehension does the same loop in one expression.
Learn the concept
New to this topic? Read the lesson, then come back.