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

This is a Python Program to create a list of tuples with the first element as the number and the second element as the square of the number.

Problem Description

The program takes a range and creates a list of tuples within that range with the first element as the number and the second element as the square of the number.

Problem Solution

1. Take the upper and lower range for the numbers from the user.
2. A list of tuples must be created using list comprehension where the first element is the number within the range and the second element is the square of the number.
3. This list of tuples is then printed.
4. Exit.

Program/Source Code

Here is source code of the Python Program to create a list of tuples with the first element as the number and the second element as the square of the number. The program output is also shown below.

l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)
Program Explanation

1. User must enter the upper and lower range for the numbers.
2. List comprehension must be used to create a list of tuples where the first number is the number itself from the given range and the second element is a square of the first number.
3. The list of tuples which is created is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter the lower range:1
Enter the upper range:4
[(1, 1), (2, 4), (3, 9), (4, 16)]
 
Case 2:
Enter the lower range:45
Enter the upper range:49
[(45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401)]

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.