In this course, we will take a closer look at one of the important control structures in Python, the for
loop. The for
loop is primarily used to iterate over a specific range of values. In Python, the for
loop is useful for traversing sequences (lists, tuples, strings, etc.) and helps to efficiently handle repetitive tasks.
1. Basic Structure of for Loop
The for
loop in Python is designed to repeatedly execute a specific block of code for each element in a sequence. The basic structure is as follows:
for variable in sequence:
code to execute
Here, “variable” will receive one element of the sequence in each iteration, and “code to execute” contains the actual tasks to perform.
2. Example: Iterating Over a List
Let’s take a look at the most basic example of iterating over a list.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
This code will print each fruit name from the fruits
list. The output will be as follows:
apple
banana
cherry
3. Using for Loop with range() Function
The range()
function is mainly used with the for
loop to repeat code a specified number of times. It has the syntax range(start, stop[, step])
, and the parameters are as follows:
start
: The number where the count begins. The default is 0.stop
: The number where the count ends (not included).step
: The interval between counts. The default is 1.
Let’s understand this with an example:
for i in range(3):
print(i)
Output:
0
1
2
4. Nested for Loops
A nested for
loop simply means having another for
loop inside a for
loop. Here is an example of a nested for
loop that iterates over a two-dimensional list:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for num in row:
print(num)
This code will print all the numbers in the 2D list.
5. for Loop and else
Surprisingly, in Python, the for
loop can be used with else
. You can write code in the else
block that will execute when the for
loop has completed normally. Let’s see the following example:
for fruit in fruits:
if fruit == 'banana':
print('Banana found!')
break
else:
print('No bananas.')
In this case, ‘Banana found!’ will be printed, demonstrating how the for-else
construct works.
6. Using with enumerate()
The enumerate()
function helps to deal with both index and elements simultaneously when iterating through a sequence. Let’s take a closer look with the following example:
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
7. Using Break to Avoid Infinite Loops
If you want to stop the for
loop under certain conditions, you can use the break
statement. This helps avoid infinite loops or unnecessary iterations.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
8. Performance Considerations
When using multiple loops, performance should be considered. Especially with large datasets, nested loops can adversely affect performance. Here are some tips to minimize this:
- Use list comprehensions when possible.
- Utilize ‘break’ and ‘continue’ statements appropriately to avoid unnecessary iterations.
9. for Loop and List Comprehensions
List comprehensions are a way to create lists more concisely. They can be shorter than loops and sometimes faster:
numbers = [1, 2, 3, 4, 5]
squared = [n**2 for n in numbers]
print(squared)
Output:
[1, 4, 9, 16, 25]
Conclusion
The for
loop in Python is an essential tool for traversing and processing various data structures and greatly aids in writing efficient code. Understanding the various uses of the for
loop and applying them to actual code is important for writing effective code.