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
Selected Reading
Python Program to Get K initial powers of N
When it is required to get the specific number of powers of a number, the ** operator is used along with list comprehension to generate the first K powers of N.
Syntax
The basic syntax for calculating powers in Python ?
# Using ** operator result = base ** exponent # Using list comprehension for multiple powers powers = [base ** i for i in range(k)]
Example
Below is a demonstration of getting K initial powers of N ?
n = 4
k = 5
print("The value n is:", n)
print("The value of k is:", k)
result = [n ** index for index in range(0, k)]
print("The first", k, "powers of", n, ":")
print(result)
The value n is: 4 The value of k is: 5 The first 5 powers of 4 : [1, 4, 16, 64, 256]
How It Works
The list comprehension iterates through numbers from 0 to k-1:
40 = 1
41 = 4
42 = 16
43 = 64
44 = 256
Using a Function
You can create a reusable function for this operation ?
def get_k_powers(n, k):
"""Return first k powers of n"""
return [n ** i for i in range(k)]
# Example usage
base = 3
count = 6
powers = get_k_powers(base, count)
print(f"First {count} powers of {base}:")
for i, power in enumerate(powers):
print(f"{base}^{i} = {power}")
First 6 powers of 3: 3^0 = 1 3^1 = 3 3^2 = 9 3^3 = 27 3^4 = 81 3^5 = 243
Conclusion
Use list comprehension with the ** operator to efficiently generate the first K powers of any number N. The pattern [n ** i for i in range(k)] creates powers from n0 to nk-1.
Advertisements
