- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements