A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Given a list of numbers. write a program python to turn every item of a list into its square.
Q:

Given a list of numbers. write a program python to turn every item of a list into its square.

0

Turn every item of a list into its square

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]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

  • Create an empty result list
  • Iterate a numbers list using a loop
  • In each iteration, calculate the square of a current number and add it to the result list using the append() method.
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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now