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
Create a list of tuples from given list having number and its cube in each tuple using Python
When it is required to create a list from a given list that have a number and its cube, list comprehension can be used. This approach creates tuples containing each number and its cube (number raised to the power of 3).
Using List Comprehension with pow()
The pow() function calculates the power of a number. Here we use pow(val, 3) to get the cube ?
my_list = [32, 54, 47, 89]
print("The list is:")
print(my_list)
my_result = [(val, pow(val, 3)) for val in my_list]
print("The result is:")
print(my_result)
The list is: [32, 54, 47, 89] The result is: [(32, 32768), (54, 157464), (47, 103823), (89, 704969)]
Alternative Method Using ** Operator
You can also use the ** operator for exponentiation ?
numbers = [2, 3, 5, 7]
result = [(num, num**3) for num in numbers]
print("Number and cube pairs:")
print(result)
Number and cube pairs: [(2, 8), (3, 27), (5, 125), (7, 343)]
Using a Function Approach
For more complex operations, you can define a function ?
def create_cube_pairs(numbers):
return [(num, num**3) for num in numbers]
data = [1, 4, 6, 10]
cube_pairs = create_cube_pairs(data)
print("Original list:", data)
print("Cube pairs:", cube_pairs)
Original list: [1, 4, 6, 10] Cube pairs: [(1, 1), (4, 64), (6, 216), (10, 1000)]
How It Works
The list comprehension [(val, pow(val, 3)) for val in my_list] works as follows:
Iterates through each element
valin the original listCreates a tuple
(val, pow(val, 3))for each elementThe
pow(val, 3)calculates val³ (cube of the number)Collects all tuples into a new list
Conclusion
List comprehension with pow() or ** operator efficiently creates tuples of numbers and their cubes. This approach is concise and readable for mathematical transformations.
