Python Practice › Tuple Programs › Program 4
List of (number, square) tuples
Write a Python program to create a list of tuples, each holding a number and its square.
Input
[4, 6, 3, 8]
Output
[(4, 16), (6, 36), (3, 9), (8, 64)]
Approach
- A comprehension builds
(n, n * n)for each number.
Solution
numbers = [4, 6, 3, 8]print([(n, n * n) for n in numbers])Output
[(4, 16), (6, 36), (3, 9), (8, 64)]
Note
The square of 3 is 9; the original sample showed 27, which is 3 cubed.
Learn the concept
New to this topic? Read the lesson, then come back.