Python: Square the elements of a list using map()
5. Square Elements 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]
For more Practice: Solve these Related Problems:
- Write a Python program to square each even element in a list and leave odd elements unchanged using map.
- Write a Python program to square every element and then subtract one from each result using the map() function.
- Write a Python program to square each element and then compute its remainder when divided by 10 using map.
- Write a Python program to square each number in a list and convert the squared values into strings using map.
Go to:
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.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.