Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number


When it is required to create a list of tuple, and have the first element as the number, and the second element as the square of the element, list comprehension can be used.

Below is the demonstration of the same −

Example

 Live Demo

my_list = [23, 42, 67, 89, 11, 32]
print(“The list is “)
print(my_list)
print(“The resultant tuple is :”)
my_result = [(val, pow(val, 2)) for val in my_list]
print(my_result)

Output

The list is
[23, 42, 67, 89, 11, 32]
The resultant tuple is :
[(23, 529), (42, 1764), (67, 4489), (89, 7921), (11, 121), (32, 1024)]

Explanation

  • A list is defined, and is displayed on the console.

  • The list comprehension is used and the ‘pow’ method is used to find the square of the number.

  • This is converted to a list.

  • The output is displayed on the console.

Updated on: 19-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements