Python List All Squares of a Number List
We will use Python to write a simple program that accepts a list of numbers and returns a list of their squares.
Example
numbers
=
[
1
,
2
,
3
,
4
,
5
]
squares
=
[
n**
2
for
n
in
numbers
]
(
squares
)
Code analysis:
numbers = [1, 2, 3, 4, 5]: Define a list containing the numbers 1 to 5.squares = [n**2 for n in numbers]: use a list comprehension to iterate overnumberseach element in the listn, and compute its squaren**2, then store the result insquareslist.print(squares): Print thesquareslist, i.e., the square of each number.
Output result:
Example
[
1
,
4
,
9
,
16
,
25
]
Python3 Examples