How can you use a for loop to create a list of squares of numbers from 1 to 5?
hard📝 Application Q9 of 15
Python - For Loop
How can you use a for loop to create a list of squares of numbers from 1 to 5?
Asquares = []
for i in range(1, 6):
squares.append(i * i)
Bsquares = [i * i for i in range(1, 5)]
Csquares = []
for i in range(5):
squares.append(i * i)
Dsquares = []
for i in range(1, 6):
squares.add(i ** 2)
Step-by-Step Solution
Solution:
Step 1: Understand range and list building
range(1,6) gives numbers 1 to 5; append adds items to list.
Step 2: Check each option for correctness
squares = []
for i in range(1, 6):
squares.append(i * i) correctly appends squares of 1 to 5. squares = [i * i for i in range(1, 5)] misses 5. squares = []
for i in range(5):
squares.append(i * i) starts at 0. squares = []
for i in range(1, 6):
squares.add(i ** 2) uses add() which is invalid for lists.
Final Answer:
squares = []\nfor i in range(1, 6):\n squares.append(i * i) -> Option A
Quick Check:
Use append() to add items to list [OK]
Quick Trick:Use append() to build lists in loops [OK]
Common Mistakes:
MISTAKES
Wrong range limits
Using add() on list
Off-by-one errors
Master "For Loop" in Python
9 interactive learning modes - each teaches the same concept differently