Python Program: Create a List of Tuples with Number and Its Cube
Introduction
In this blog post, we will explore how to write a Python program to create a list of tuples where each tuple contains a number and its cube. We’ll discuss the algorithm, provide a step-by-step explanation, present the Python code, and include examples with outputs.
Understanding the Algorithm
The algorithm for creating a list of tuples involves the following steps:
Input List: Take a list of numbers as input.
Create Tuples: For each number in the input list, create a tuple containing the number and its cube.
Build Result List: Append the tuples to a new list.
Output Result: Display the list of tuples as the output.
Python Program to Create a List of Tuples with Number and Its Cube
Let’s implement the algorithm in a Python program:
def create_tuples_with_cubes(input_list):
# Create list of tuples with number and its cube
result_list = [(num, num**3) for num in input_list]
return result_list
# Example Usage
numbers_list = [1, 2, 3, 4, 5]
result_tuples = create_tuples_with_cubes(numbers_list)
print("List of Tuples with Number and Its Cube:")
for tpl in result_tuples:
print(tpl)
Output Example
Example: Create List of Tuples with Number and Its Cube
List of Tuples with Number and Its Cube:
(1, 1)
(2, 8)
(3, 27)
(4, 64)
(5, 125)
Explanation
The program defines a function create_tuples_with_cubes
that takes a list of numbers as input. It uses a list comprehension to create a new list of tuples where each tuple contains a number and its cube. The example uses the input list [1, 2, 3, 4, 5]
, and the output displays the resulting list of tuples.
Conclusion
Creating a list of tuples in Python is a common task, and it can be achieved elegantly using list comprehensions. This program demonstrates how to generate tuples with numbers and their cubes, offering a practical example of list manipulation.
Feel free to experiment with the code and try it with different input lists. If you have any questions, encounter issues, or want to explore more about Python programming, tuples, or list comprehensions, feel free to ask!