In this tutorial, we will learn How to square the elements of a list in Python.
Explanation ✏
- First, create a list of n numbers
- Then, create another blank list for storing a square list
- Now, with the help of for loop append each number in the blank list
- 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])