Python Program to Display Powers of 2 Using Lambda Function – 2024

Python Tutorials MLP Feature Image

Hey guys, in this blog we will see a Python Program to Display Powers of 2 Using Lambda Function.

Code

# Python Program to Display Powers of 2 Using Lambda Function

terms = int(input("How many terms? "))

# use lambda function
result = list(map(lambda x: 2 ** x, range(terms)))

for i in range(terms):
    print(f"2 raised to power {i} is {result[i]}")

Output

How many terms? 5
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
How many terms? 6
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
How many terms? 7
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
  • Here we have simply used the lambda function to create a list of results.
  • What we are doing is we have created a list of numbers using the range function. For eg. range(5) will give [0,1,2,3,4].
  • Then we are using the map function to map the lambda function to each and every element of this list.
  • Finally, we will create a list from this map generator object.

Check out our other python programming examples

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top