Python program to print the square of all elements in a list

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

In this tutorial, we will learn How to square the elements of a list in Python.

Explanation ✏

  1. First, create a list of n numbers
  2. Then, create another blank list for storing a square list
  3. Now, with the help of for loop append each number in the blank list
  4. Finally just print the list.

Code 👩‍💻

def squareList():
      nums = [1,2,3,4,5,6,7,8,9,10]
      my_list = []
      for n in nums:
           my_list.append(n*n)
      print(my_list)
squareList()

💡 You can also write this program with the help of list comprehension, in just two lines

Code 👩‍💻

nums = [1,2,3,4,5,6,7,8,9,10]
print([i*i for i in nums])

Comments (2)

Siddharth Chandra's photo

One more way is to use lazy evaluation:

map(lambda x: x*x, num))

Nishant Tiwari's photo

yes correct 😃