Sure! Here's a simple Python example that demonstrates how to create a list of numbers and then use a list comprehension to create a new list containing the squares of those numbers.
Example: Squaring Numbers in a List
# Original list of numbers
numbers = [1, 2, 3, 4, 5]
# Using list comprehension to create a new list of squares
squares = [x**2 for x in numbers]
# Print the result
print("Original numbers:", numbers)
print("Squared numbers:", squares)
Explanation:
- Original List: We start with a list called
numberscontaining integers from 1 to 5. - List Comprehension: The line
[x**2 for x in numbers]creates a new list calledsquaresby iterating over each numberxin thenumberslist and squaring it (x**2). - Output: Finally, we print both the original and squared lists.
Feel free to run this code in your Python environment or ask if you have any questions about it!
