Skip to main content

Command Palette

Search for a command to run...

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

Updated
1 min read
Python program to print the square of all elements in a list
N

It has now been seven years since I am exploring my ways in the world of New Age technology. In all these years, what is my favourite thing in the whole world? I would say my keyboard! If it’s a war, I got my code as the skill and my keyboard as the weapon. When I was a kid, I wondered what it would feel like to be a hacker. I kept feeding my curiosity in the bits and pieces. I was getting introduced with new things everyday and over time. All this passion has made me targeted towards my main objective, that is, to learn everything which is out there about computer. For now, I have got a good grip over Python, JavaScript, C and C++. I think the main reason for my motivation is that I strongly believe, if you keep your mind clear and devote yourself to pure learning, there will come a time when your own reality will get surrounded by your self-made uniqueness.

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])
S

One more way is to use lazy evaluation:

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

2
N

yes correct 😃

2