Use a list comprehension to get a square of each list element in Python. The list comprehension returns a new list containing squared elements.
Example 1
numbers = [11, 21, 19, 30, 46]
squaredValues = [number ** 2 for number in numbers]
print('Original Values: ', numbers)
print('Squared Values: ', squaredValues)
Output
Original Values: [11, 21, 19, 30, 46]
Squared Values: [121, 441, 361, 900, 2116]
This example first makes a list of named numbers. Its contents are various integer values.
Then we generate a new list with a list comprehension. The code between square brackets ([ and ]) squares each number value with the exponent (**) operator.
Those number values are generated by an in-line for loop expression: for the number in numbers. This goes through our original numbers list and makes each element available as the number variable, one at a time.
After that list comprehension, the squared list has each value squared. We then output the original and squared values with the print() function.
We could also get the square values differently. For instance, with simple multiplication, you can achieve your result.
Example 2
numbers = [11, 21, 19, 30, 46]
squaredValues = [number * number for number in numbers]
print('Original Values: ', numbers)
print('Squared Values: ', squaredValues)
Output
Original Values: [11, 21, 19, 30, 46]
Squared Values: [121, 441, 361, 900, 2116]
In this example, we have defined a list and then used list comprehension to create the square of list items.