This document explains Python loops, including for and while loops, with practical examples using lists, tuples, and the range function. It covers loop syntax, iteration methods, and common use cases for data manipulation.
This document explores Python loops, focusing on for and while loops, the range and enumerate functions, and practical techniques for iterating and manipulating data in lists and tuples. Readers will learn loop syntax, control flow, and common patterns for data processing.
Loops in Python allow repeated execution of code blocks, making it possible to process sequences of data efficiently. The two main types are for loops and while loops, each suited for different scenarios.
The range() function generates ordered sequences, commonly used in loops. Its behavior depends on the number of arguments:
| Input | Output Sequence |
|---|---|
| range(3) | 0, 1, 2 |
| range(10,15) | 10, 11, 12, 13, 14 |
range() returns a range object, not a list. To convert to a list, use list(range(...)).For loops iterate over sequences such as lists or tuples. They can use indices or directly access elements.
To update each element in a list:
1colors = ["red", "yellow", "green", "blue", "orange"]
2for i in range(len(colors)):
3 colors[i] = "white"
For loops can also iterate directly over elements:
1squares = ["red", "yellow", "green"]
2for square in squares:
3 print(square)
square.The enumerate() function provides both index and value:
1squares = ["red", "yellow", "green"]
2for i, square in enumerate(squares):
3 print(i, square)
| Iteration | Index (i) | Value (square) |
|---|---|---|
| 1 | 0 | red |
| 2 | 1 | yellow |
| 3 | 2 | green |
While loops execute as long as a condition remains true. Useful when the number of iterations is not known in advance.
1squares = ["orange", "orange", "purple"]
2new_squares = []
3i = 0
4while i < len(squares) and squares[i] == "orange":
5 new_squares.append(squares[i])
6 i += 1
Loops are fundamental in Python for processing sequences and automating repetitive tasks. Mastery of for and while loops, along with range and enumerate, enables efficient data handling and algorithm implementation.
- The enumerate() function provides both the index and the value for each element in a sequence during iteration.
| Loop Type | Characteristic |
|---|---|
| A. For loop | 1. Continues while a condition is true |
| B. While loop | 2. Iterates over a sequence for a set number of times |
A-2, B-1.
The range() function in Python 3 returns a range object, not a list, and must be converted using list(range(…)) for list operations.
True. In Python 3, range() returns a range object, which can be converted to a list if needed.
- For loops do not require manual index management unless specifically using indices.