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 compute the power by Index element in List
When it is required to compute the power by index element in a list, we can use iteration along with the ** operator to raise each element to the power of its index position.
Understanding the Concept
In this operation, each element at index i is raised to the power i. For example, element at index 0 becomes element ** 0 = 1, element at index 1 becomes element ** 1 = element, and so on.
Using enumerate() with List Iteration
The most straightforward approach uses enumerate() to get both index and element ?
my_list = [62, 18, 12, 63, 44, 75]
print("The list is:")
print(my_list)
my_result = []
for my_index, elem in enumerate(my_list):
my_result.append(elem ** my_index)
print("The result is:")
print(my_result)
The list is: [62, 18, 12, 63, 44, 75] The result is: [1, 18, 144, 250047, 3748096, 2373046875]
Using List Comprehension
A more concise approach using list comprehension ?
my_list = [62, 18, 12, 63, 44, 75]
my_result = [elem ** idx for idx, elem in enumerate(my_list)]
print("Original list:", my_list)
print("Power by index:", my_result)
Original list: [62, 18, 12, 63, 44, 75] Power by index: [1, 18, 144, 250047, 3748096, 2373046875]
Using range() with Index Access
Alternative approach using range() and direct index access ?
my_list = [62, 18, 12, 63, 44, 75]
my_result = []
for i in range(len(my_list)):
my_result.append(my_list[i] ** i)
print("Original list:", my_list)
print("Result:", my_result)
Original list: [62, 18, 12, 63, 44, 75] Result: [1, 18, 144, 250047, 3748096, 2373046875]
How It Works
The calculation for each element follows this pattern:
- Index 0:
62 ** 0 = 1(any number to power 0 equals 1) - Index 1:
18 ** 1 = 18(any number to power 1 equals itself) - Index 2:
12 ** 2 = 144 - Index 3:
63 ** 3 = 250047 - Index 4:
44 ** 4 = 3748096 - Index 5:
75 ** 5 = 2373046875
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
enumerate() |
Good | Standard | Clear, readable code |
| List comprehension | Excellent | Fastest | Concise, Pythonic approach |
range() |
Fair | Slightly slower | When index is needed elsewhere |
Conclusion
Use list comprehension with enumerate() for the most Pythonic approach. The enumerate() method provides clear, readable code when you need both index and element values for computation.
