belongs to collection: Python List Exercises
Given a list of numbers. write a program to turn every item of a list into its square.
Given:
numbers = [1, 2, 3, 4, 5, 6, 7]
Expected output:
[1, 4, 9, 16, 25, 36, 49]
Hint:
Iterate numbers from a list one by one using a for loop and calculate the square of the current number
Solution1:Using loop and list method
append()
numbers = [1, 2, 3, 4, 5, 6, 7] # result list res = [] for i in numbers: # calculate square and add to the result list res.append(i * i) print(res)
Solution2:Use list comprehension
numbers = [1, 2, 3, 4, 5, 6, 7] res = [x * x for x in numbers] print(res)
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Hint:
Iterate numbers from a list one by one using a for loop and calculate the square of the current number
Solution1:Using loop and list method
append()
method.Solution2:Use list comprehension
need an explanation for this answer? contact us directly to get an explanation for this answer