
Python
The most powerful use of loops: efficiently processing every item in a list.
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Output: apple, banana, orangeExample 1: Process each item
scores = [85, 92, 78, 95]
for score in scores:
print(f"Score: {score}")Example 2: Modify items
numbers = [1, 2, 3, 4]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2 # Double each number
print(numbers) # [2, 4, 6, 8]Example 3: Calculate total
prices = [10.99, 5.50, 25.00]
total = 0
for price in prices:
total = total + price
print(f"Total: ${total}") # Total: $41.49fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: orangeExample 1: Find position of item
grades = ["A", "B", "C", "B", "A"]
for index, grade in enumerate(grades):
if grade == "C":
print(f"C grade at position {index}")Example 2: Update specific items
items = ["apple", "banana", "orange"]
for index, item in enumerate(items):
if item == "banana":
items[index] = "pear"
print(items) # ['apple', 'pear', 'orange']| Method | Use Case | Example |
|---|---|---|
| `for item in list:` | Get each value | `for x in [1,2,3]:` |
| `for index, item in enumerate(list):` | Get index + value | `for i, x in enumerate(list):` |
| `for i in range(len(list)):` | Get index for modification | `list[i] = new_value` |
| Concept | Remember |
|---|---|
| Iterating | Easiest way to process all items |
| enumerate() | Gets both index and value |
| len() | Gets number of items in list |
| Direct vs Index | Use direct access unless modifying |
Learn Loop Patterns for common use cases!
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward