Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 you need to create a list of tuples where each tuple contains a number and its square, Python provides several approaches. The most common methods are list comprehension, using loops, and the map() function.
Using List Comprehension
List comprehension provides a concise way to create the list of tuples ?
numbers = [23, 42, 67, 89, 11, 32]
print("The list is:")
print(numbers)
result = [(num, pow(num, 2)) for num in numbers]
print("The resultant tuples are:")
print(result)
The list is: [23, 42, 67, 89, 11, 32] The resultant tuples are: [(23, 529), (42, 1764), (67, 4489), (89, 7921), (11, 121), (32, 1024)]
Using a For Loop
A traditional for loop approach for better readability ?
numbers = [5, 8, 12, 15]
result = []
for num in numbers:
result.append((num, num ** 2))
print("Numbers and their squares:")
print(result)
Numbers and their squares: [(5, 25), (8, 64), (12, 144), (15, 225)]
Using map() Function
The map() function can be used with a lambda function ?
numbers = [3, 6, 9, 12]
result = list(map(lambda x: (x, x**2), numbers))
print("Using map function:")
print(result)
Using map function: [(3, 9), (6, 36), (9, 81), (12, 144)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Most cases |
| For Loop | Very High | Moderate | Complex logic |
| map() Function | Moderate | Fast | Functional programming |
Conclusion
List comprehension is the most Pythonic way to create tuples of numbers and their squares. Use for loops when you need more complex operations, and map() for functional programming approaches.
Advertisements
