In this example, you will learn how to compute the powers of 2 using three different methods.
- Using lambda function
- Using a named function
- Using a for loop
Using the Anonymous lambda function
In this example, we pass a lambda function that computes the square of a number to a map function and returns a list with the square of each number
terms = 10
result = list(map(lambda x: 2 ** x, range(terms)))
print("Using Lambda Function:")
for i in range(terms):
print("2 raised to power", i, "is", result[i])
Output
Using Lambda Function:
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512
Here we use an anonymous function, also known as a lambda function, to display the powers of 2. here, we define a lambda function that takes an argument n and returns 2 raised to the power of n. We then use a for loop to iterate through a range of numbers from 0 to 10 and call the lambda function for each number, printing out the result.
Using a named function
# using named function
def power_of_two(n):
return lambda x: x**n
terms = 10
result = list(map(power_of_two(2), range(terms)))
print("Using a Named Function:")
for i in range(terms):
print("2 raised to power", i, "is", result[i])
Output
Using a Named Function:
2 raised to power 0 is 0
2 raised to power 1 is 1
2 raised to power 2 is 4
2 raised to power 3 is 9
2 raised to power 4 is 16
2 raised to power 5 is 25
2 raised to power 6 is 36
2 raised to power 7 is 49
2 raised to power 8 is 64
2 raised to power 9 is 81
Using Python for loops
# using for loop
terms = 10
result = []
for i in range(terms):
result.append(2 ** i)
print("Using For Loop:")
for i in range(terms):
print("2 raised to power", i, "is", result[i])
Using For Loop:
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512