w3resource

Python: Square the elements of a list using map()

Python map: Exercise-5 with Solution

Write a Python program to square the elements of a list using map() function.

Sample Solution:

Python Code :

def square_num(n):
  return n * n
nums = [4, 5, 2, 9]
print("Original List: ",nums)
result = map(square_num, nums)
print("Square the elements of the said list using map():")
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 Python skills with w3resource's quiz



Python: Tips of the Day

Merging two dicts in Python 3.5+ with a single expression

Example:

# How to merge two dictionaries
# in Python 3.5+

x = {'p': 1, 'q': 3}
y = {'q': 5, 'r': 8}

z = {**x, **y}

z
{'r': 4, 'p': 1, 'q': 3}

z = dict(x, **y)
print(z)

Output:

{'p': 1, 'q': 5, 'r': 8}