Iteration in Python
Iteration in Python allows you to execute a block of code repeatedly. Below are the key methods and constructs used for iteration:
---
**1. `for` Loop**
Iterates over items in an iterable (e.g., lists, tuples, strings, dictionaries).
**Syntax**:
```python
for item in iterable:
# Code block
```
**Example**:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
**Using `range()`** (for numerical ranges):
```python
for i in range(5): # 0 to 4
print(i)
```
---
**2. `while` Loop**
Repeats code while a condition is `True`.
**Syntax**:
```python
while condition:
# Code block
```
**Example**:
```python
count = 3
while count > 0:
print(count)
count -= 1 # Output: 3, 2, 1
```
**Avoid Infinite Loops**: Ensure the condition eventually becomes `False`.
---
**3. Iterables vs. Iterators**
- **Iterable**: An object that can return an iterator (e.g., lists, strings).
- **Iterator**: An object with state, producing values via `next()`.
**Manually Using Iterators**:
```python
numbers = iter([1, 2, 3])
print(next(numbers)) # 1
print(next(numbers)) # 2
# Raises StopIteration when exhausted
```
---
**4. List Comprehensions**
Concise way to create lists using iteration.
**Example**:
```python
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
```
---
**5. `enumerate()`**
Get both index and value during iteration.
**Example**:
```python
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
```
---
**6. `zip()`**
Iterate over multiple sequences in parallel.
**Example**:
```python
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
```
---
**7. Loop Control Statements**
- **`break`**: Exit the loop immediately.
- **`continue`**: Skip to the next iteration.
- **`else`**: Execute if the loop completes normally (no `break`).
**Example**:
```python
for num in range(10):
if num == 5:
break # Exits loop at 5
print(num)
else:
print("Loop finished") # Not executed due to break
```
---
**8. Generators**
Create iterators using `yield` for memory efficiency.
**Example**:
```python
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for num in count_up_to(3):
print(num) # 1, 2, 3
```
---
**9. Nested Loops**
Loops inside other loops (e.g., for matrices).
**Example**:
```python
matrix = [[1, 2], [3, 4]]
for row in matrix:
for num in row:
print(num) # 1, 2, 3, 4
```
---
**10. Iterating Dictionaries**
- **Keys**: `for key in dict`
- **Values**: `for value in dict.values()`
- **Key-Value Pairs**: `for key, value in dict.items()`
**Example**:
```python
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(f"{key}: {value}")
```
---
**Summary Table**
| Method | Use Case |
|-----------------------|-----------------------------------------------|
| `for` loop | Iterating over iterables (lists, strings, etc.) |
| `while` loop | Repeating until a condition fails |
| `enumerate()` | Accessing index and value together |
| `zip()` | Iterating over multiple sequences in parallel |
| List comprehensions | Creating lists concisely |
| Generators | Memory-efficient iteration with `yield` |
Iteration is fundamental in Python, enabling efficient and readable handling of repetitive tasks.
Comments
Post a Comment