Can you provide a Python example?

QuestionsQuestions8 SkillsProYour First Linux LabNov, 06 2025
085

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 numbers containing integers from 1 to 5.
  • List Comprehension: The line [x**2 for x in numbers] creates a new list called squares by iterating over each number x in the numbers list 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!

0 Comments

no data
Be the first to share your comment!