Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to find the cube of each list element
Finding the cube of each list element is a common operation in Python. We can achieve this using several approaches: simple iteration with append(), list comprehension, or the map() function.
Method 1: Using Simple Iteration
This approach uses a for loop to iterate through each element and append the cubed value to a new list ?
numbers = [45, 31, 22, 48, 59, 99, 0]
print("The list is:")
print(numbers)
cubed_numbers = []
for num in numbers:
cubed_numbers.append(num * num * num)
print("The resultant list is:")
print(cubed_numbers)
The list is: [45, 31, 22, 48, 59, 99, 0] The resultant list is: [91125, 29791, 10648, 110592, 205379, 970299, 0]
Method 2: Using List Comprehension
List comprehension provides a more concise and Pythonic way to create the cubed list ?
numbers = [45, 31, 22, 48, 59, 99, 0]
print("The list is:")
print(numbers)
cubed_numbers = [num ** 3 for num in numbers]
print("The resultant list is:")
print(cubed_numbers)
The list is: [45, 31, 22, 48, 59, 99, 0] The resultant list is: [91125, 29791, 10648, 110592, 205379, 970299, 0]
Method 3: Using map() Function
The map() function applies a lambda function to each element of the list ?
numbers = [45, 31, 22, 48, 59, 99, 0]
print("The list is:")
print(numbers)
cubed_numbers = list(map(lambda x: x ** 3, numbers))
print("The resultant list is:")
print(cubed_numbers)
The list is: [45, 31, 22, 48, 59, 99, 0] The resultant list is: [91125, 29791, 10648, 110592, 205379, 970299, 0]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Simple Iteration | Good | Moderate | Beginners, complex logic |
| List Comprehension | Excellent | Fast | Most Python operations |
| map() Function | Good | Fast | Functional programming |
Explanation
The original list contains integers that need to be cubed.
Each method creates a new list with cubed values.
Cubing is performed using
num * num * numornum ** 3.List comprehension is generally preferred for its conciseness and readability.
Conclusion
List comprehension is the most Pythonic approach for cubing list elements due to its conciseness and readability. Use simple iteration when you need more complex logic or are teaching basic concepts.
