How to Cube a List in Python

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:

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:

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:

After applying the cubing function, you can print the original and new lists using the print function:

Your Full Code:

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.