Python For Loops
For loops are an essential part of Python programming, allowing you to iterate over a sequence of elements and perform actions on each one. In this tutorial, you'll learn everything you need to know about for loops in Python.
For Loop Syntax
A for loop in Python iterates over a sequence of elements, such as a list, tuple, or string. Here is the basic syntax for a for loop:
for element in sequence: # loop body
Here, element is a variable that takes on the value of each element in the sequence one by one, and the indented block of code under the for statement, known as the loop body, is executed for each element.
For example, consider the following for loop that iterates over a list of numbers and prints each one:
numbers = [1, 2, 3, 4, 5] for number in numbers: print(number)
This will output the following:
1 2 3 4 5
You can use any variable name you like for the loop variable, but it's common to use a descriptive name like number or element.
Best Practices for Loop Declaration
- Use a descriptive variable name for the loop variable to make the code more readable.
- Avoid using the same variable name for the loop variable and a variable used in the loop body, as this can cause confusion.
For Loop Characteristics
There are a few important characteristics of for loops in Python:
- The loop body is executed once for each element in the sequence.
- The loop variable takes on the value of each element in the sequence, one by one.
- The loop continues until it has iterated over all elements in the sequence.
- If the sequence is empty, the loop body is not executed at all.
For example, consider the following loop that iterates over a list of strings and prints each one:
names = ['Alice', 'Bob', 'Charlie', 'Debbie'] for name in names: print(name)
This will output the following:
Alice Bob Charlie Debbie
Sometimes you may want to prematurely exit a loop or skip an iteration. Python provides two statements for this purpose: break and continue.
The break statement exits the loop completely, while the continue statement ends the current iteration and moves on to the next one.
Here is an example of using break to exit a loop early:
for number in range(1, 10): if number % 2 == 0: break print(number)
The loop is terminated as soon as it encounters an even number, because the break statement is executed when the condition number % 2 == 0 is true.
Here is an example of using continue to skip an iteration:
for number in range(1, 10): if number % 2 == 0: continue print(number)
1 3 5 7 9
The loop continues to iterate over all numbers in the range, but the continue statement skips the iterations where the number is even, so only the odd numbers are printed.
Best Practices for Manipulation
- Use break and continue sparingly, as they can make your code harder to read and understand.
- Make sure that the conditions under which break and continue are used are clear and easy to understand.
Loop Through a List with Subsections
There are a few useful techniques for iterating over a list in Python that you may find helpful.
The enumerate function allows you to iterate over a list and also keep track of the index of each element. Here is an example of using enumerate in a for loop:
words = ['apple', 'banana', 'cherry'] for i, word in enumerate(words): print(i, word)
0 apple 1 banana 2 cherry
Here, the loop variable i takes on the value of the index for each element, and the loop variable word takes on the value of each element. This can be useful if you need to access both the element and its index in the loop body.
You can also use slicing to iterate over a subset of a list. For example, to iterate over every other element of a list, you can use the following syntax:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for number in numbers[::2]: print(number)
1 3 5 7 9
The slice [::2] means "start at the beginning of the list, go to the end, and skip every other element." This allows you to iterate over every other element of the list.
You can also specify a range of indices to iterate over. For example, to iterate over the first three elements of a list, you can use the following syntax:
words = ['apple', 'banana', 'cherry', 'date', 'elderberry'] for word in words[:3]: print(word)
apple banana cherry
The slice [:3] means "start at the beginning of the list and go up to, but not including, the element at index 3." This allows you to iterate over the first three elements of the list.
Best Practices when Looping through iterable
- Use enumerate if you need to access both the element and its index in the loop body.
- Use slicing to iterate over subsets of a list, but be careful to use the correct indices to avoid going out of bounds.
- Make sure that the slice you are using is the correct length and starts and ends at the correct indices.