Python: Square the elements of a list using map()
Write a Python program to square the elements of a list using the map() function.
Sample Solution:
Python Code :
# Define a function named square_num that calculates the square of a given number 'n'
def square_num(n):
return n * n
# Create a list named 'nums' containing integer elements
nums = [4, 5, 2, 9]
# Print the original list of numbers
print("Original List: ", nums)
# Use the map function to apply the square_num function to each element of 'nums'
result = map(square_num, nums)
# Print a message indicating the operation to be performed
print("Square the elements of the said list using map():")
# Print the result of the map operation as a list
print(list(result))
Sample Output:
Original List: [4, 5, 2, 9] Square the elements of the said list using map(): [16, 25, 4, 81]
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to create a list containing the power of said number in bases raised to the corresponding number in the index using Python map.
Next: Write a Python program to convert all the characters in uppercase and lowercase and eliminate duplicate letters from a given sequence. Use map() function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics