![]() |
VOOZH | about |
Given a list of numbers, the task is to create a list of tuples where each tuple contains a number and its cube. For example:
Input: [1, 2, 3]
Output: [(1, 1), (2, 8), (3, 27)]
Let’s explore different methods to achieve this efficiently in Python.
This method uses list comprehension to generate the tuples directly while iterating over the list.
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation:
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.
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation:
This method separates numbers and their cubes into two lists and then combines them with zip().
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation:
This method uses a standard loop to build the list incrementally.
[(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)]
Explanation: