Python Practice › List Programs › Program 1

Square of each number in a list

EasyList Programs · 1 of 100

Write a Python program to calculate the square of each number in a list.

Advertisement
Input
[2, 4, 6, 8, 10]
Output
[4, 16, 36, 64, 100]

Approach

  1. Loop over the list and append each number squared, or use a list comprehension.

Solution 1: loop

Python
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

Python
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.

More list programs

← All 100 List Programs

Leave a Comment