Python: Square and cube every number in a given list of integers using Lambda
Python Lambda: Exercise-6 with Solution
Write a Python program to square and cube every number in a given list of integers using Lambda.
Sample Solution:
Python Code :
# Create a list of integers named 'nums'
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Display a message indicating that the following output will show the original list of integers
print("Original list of integers:")
print(nums)
# Display a message indicating that the following output will show each number in the list squared
print("\nSquare every number of the said list:")
# Use the 'map()' function with a lambda function to square each number in the 'nums' list
# Create a new list 'square_nums' containing the squared values of the original list
square_nums = list(map(lambda x: x ** 2, nums))
print(square_nums)
# Display a message indicating that the following output will show each number in the list cubed
print("\nCube every number of the said list:")
# Use the 'map()' function with a lambda function to cube each number in the 'nums' list
# Create a new list 'cube_nums' containing the cubed values of the original list
cube_nums = list(map(lambda x: x ** 3, nums))
print(cube_nums)
Sample Output:
Original list of integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Square every number of the said list: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Cube every number of the said list: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Explanation:
In the exercise above -
- Initializes a list named 'nums' containing integers from 1 to 10.
- Prints the original list of integers (nums) to the console.
- Uses the "map()" function along with lambda functions to perform mathematical operations on each number in the 'nums' list:
- The code uses "map()" with a lambda function to square each number in the 'nums' list.
- It creates a new list named 'square_nums' containing the squared values of the original list.
- Then, it uses "map()" with another lambda function to cube each number in the 'nums' list.
- It creates a new list named 'cube_nums' containing the cubed values of the original list.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to filter a list of integers using Lambda.
Next: Write a Python program to find if a given string starts with a given character using Lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/lambda/python-lambda-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics