In Python, a list is a collection of items that are ordered and changeable, allowing duplicate members. Sometimes, you may want to perform certain operations on list items, like cubing each number in a list. Cubing a number in Python implies raising the number to the power of 3. This tutorial shows you how to cube a list in Python.
Step 1: Creating a list in Python
In Python, creating a list is quite simple and straightforward. You just need to place the items (elements) inside square brackets [] and separate them by commas. Here is an example:
1 2 |
# Create a list numbers = [1, 2, 3, 4, 5] |
This creates a list named ‘numbers’ with string elements 1, 2, 3, 4, and 5.
Step 2: Defining the cubing function
In Python, you can define a function to perform any action you need. In our case, we need a function that cubes each number in the list:
1 2 3 |
# Define a cubing function def cube(number): return number ** 3 |
The above code will create a cubing function that will return the cube of any given number.
Step 3: Applying the cubing function to the list
To apply the cubing function to each number in the list, we can use the Python built-in function map(). This function applies a given function to each item of an iterable (e.g., list) and returns a list of the results:
1 2 |
# Cube all numbers in the list cubed_numbers = list(map(cube, numbers)) |
After applying the cubing function, you can print the original and new lists using the print function:
1 2 3 |
# Print original and new list print('Original numbers: ', numbers) print('Cubed numbers: ', cubed_numbers) |
Your Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Create a list numbers = [1, 2, 3, 4, 5] # Define a cubing function def cube(number): return number ** 3 # Cube all numbers in the list cubed_numbers = list(map(cube, numbers)) # print original and new list print('Original numbers: ', numbers) print('Cubed numbers: ', cubed_numbers) |
Output:
Original numbers: [1, 2, 3, 4, 5] Cubed numbers: [1, 8, 27, 64, 125]
Conclusion
In this short tutorial, you learned how to cube a list in Python by defining a function and using the map function to apply the cube function to each number in the list. Remember, Python provides many built-in functions like map that can make your coding journey easier and faster.