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

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

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 11:04:09