Create a List of Tuples with Numbers and Their Cubes – Python
We are given a list of numbers and our task is to create a list of tuples where each tuple contains a number and its cube. For example, if the input is [1, 2, 3], the output should be [(1, 1), (2, 8), (3, 27)].
Using List Comprehension
List comprehension is one of the most efficient ways to achieve this task as it combines the creation of the list and computation in a single line, making the code concise and fast.
a = [1, 2, 3, 4, 5]
# Creating list of tuples using list comprehension
res = [(n, n**3) for n in a]
print(res)
Output
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation:
- [(n, n**3) for n in numbers] iterates over each element n in the list numbers.
- Each tuple contains the number n and its cube n**3.
Let’s explore some more methods and see how we can create a list of tuples from given list having number and its cube.
Using map()
map() function applies a transformation function to each element of an iterable. It can be used with a lambda function to create the desired list of tuples. This method is slightly less efficient than list comprehension due to the overhead of the lambda function.
a = [1, 2, 3, 4, 5]
# Creating list of tuples using map and lambda
res = list(map(lambda n: (n, n**3), a))
print(res)
Output
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation:
- lambda n: (n, n**3) defines an anonymous function to create tuples of (number, cube).
- map function applies the lambda to each element of numbers.
- list() converts the result of map into a list.
Using a for Loop with append()
A for loop is another simple method although slightly less concise than list comprehension, it’s easy to understand and debug.
a = [1, 2, 3, 4, 5]
# Creating list of tuples using a for loop
res = []
for n in a:
res.append((n, n**3))
print(res)
Output
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation:
- An empty list result is initialized and the loop iterates over each element n in numbers.
- The tuple (n, n**3) is appended to the result list for each iteration.
Using a Generator and list()
A generator expression can be used to produce tuples which can then be converted into a list.
a = [1, 2, 3, 4, 5]
res = list((n, n**3) for n in a)
print(res)
Output
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation:
- generator expression (n, n**3) produces tuples one at a time.
- list() function collects the generated tuples into a list.
- This method is more memory-efficient for very large datasets but slightly slower for smaller lists due to conversion overhead.