Browse Courses

Loops

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.


Introduction to Loops

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

The range() function generates ordered sequences, commonly used in loops. Its behavior depends on the number of arguments:

InputOutput Sequence
range(3)0, 1, 2
range(10,15)10, 11, 12, 13, 14
  • In Python 3, range() returns a range object, not a list. To convert to a list, use list(range(...)).

For Loops

For loops iterate over sequences such as lists or tuples. They can use indices or directly access elements.

Iterating with Indices

To update each element in a list:

1colors = ["red", "yellow", "green", "blue", "orange"]
2for i in range(len(colors)):
3    colors[i] = "white"
  • The loop runs for each index, updating the color to “white”.

Direct Iteration

For loops can also iterate directly over elements:

1squares = ["red", "yellow", "green"]
2for square in squares:
3    print(square)
  • Each iteration assigns the next element to square.

Using Enumerate

The enumerate() function provides both index and value:

1squares = ["red", "yellow", "green"]
2for i, square in enumerate(squares):
3    print(i, square)
IterationIndex (i)Value (square)
10red
21yellow
32green

While Loops

While loops execute as long as a condition remains true. Useful when the number of iterations is not known in advance.

Example: Copying Elements Until Condition Fails

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
  • The loop copies orange squares until a non-orange square is found.

Practical Notes

  • Loops are essential for data manipulation and automation.
  • The range and enumerate functions enhance loop flexibility.
  • For loops are preferred when the number of iterations is known; while loops are used when the condition is dynamic.

Conclusion

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.


FAQ

The range() function is commonly used to generate ordered sequences for iteration in Python loops. It can accept one or two arguments to define the start and end of the sequence.

For loops iterate over a sequence for a fixed number of times, while while loops continue execution as long as a specified condition remains true. For loops are preferred when the number of iterations is known, while loops are used for dynamic conditions.

  1. It generates random numbers for each loop iteration
  2. It provides both the index and the value when iterating over a sequence
  3. It sorts the elements before looping
  4. It reverses the sequence before iteration
  1. The enumerate() function provides both the index and the value for each element in a sequence during iteration.

Loop TypeCharacteristic
A. For loop1. Continues while a condition is true
B. While loop2. 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.

The loop will continue to execute indefinitely, resulting in an infinite loop that may cause the program to hang or crash.

  1. They can iterate over lists and tuples
  2. They require manual index management
  3. They can use the range function for indices
  4. They can access elements directly
  1. For loops do not require manual index management unless specifically using indices.

The loop condition should be checked first to ensure it will eventually become false, preventing infinite loops and ensuring proper termination.

Loops are essential for automating repetitive tasks and processing sequences, making them a core feature for data manipulation and algorithm development.

A while loop is most suitable for copying elements from a list until a non-matching value is found, as it allows dynamic termination based on a condition.