For Loops in Python: A Complete Guide with Examples

For loops are an essential concept in Python and programming in general. They allow you to iterate over a sequence of elements such as lists, tuples, strings and more in order to execute a block of code repeatedly.

In this comprehensive guide, we‘ll cover everything you need to know about for loops in Python with clear explanations and actionable examples for beginners and experienced programmers alike.

What Are For Loops?

A for loop allows you to efficiently repeat a set of instructions over multiple values or elements in a sequence.

The basic syntax of a for loop consists of the for keyword, followed by a variable name that will hold the current value of each iteration, the in keyword, and finally the sequence to loop over:

for item in sequence:
    # Code block to execute

Some key points about Python for loops:

  • They iterate over the elements of a sequence such as a list, tuple, string etc in order
  • The body of the loop (underneath the for line) is executed once for each item
  • You can use the loop variable item to refer to the current item
  • Common sequences to loop over include range(), list, tuples, dict keys/values and more

Now let‘s look at some examples to understand how for loops work.

Basic For Loop Examples

Let‘s start with a simple example that loops over a list of fruits and prints each one:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana  
cherry

We first create the fruits list that contains 3 string elements.

The for loop iterates over each element in fruits, assigning the variable fruit to the current item, which we simply print.

This process repeats until there are no more items left in fruits, demonstrating the basic workflow of a for loop in Python.

Let‘s try a slightly more complex example:

values = [3, 6, 9, 12]

for number in values:
    print(number*2)

Output:

6
12   
18
24

Here we have a list of numbers that we want to multiply by 2 and print. For each iteration, number takes on the next value in the list so we can perform operations using it easily inside the loop body.

We again loop through all items until finished, executing the code block each time.

The range() Function

While you can loop over sequences like we saw above, often you want to repeat a specific number of times instead.

The range() function allows us to provide a start and stop value for the sequence we want to generate, very useful for controlling loop iterations.

Let‘s print the numbers from 0 to 5 using range():

for i in range(6):
    print(i)

Output:

0
1  
2
3
4
5

range(6) generates integers from 0 up to (but not including) 6. For each iteration, i takes on values 0 through 5, which we print.

We can also define a start, stop and step size value. For example, here‘s a countdown from 10 down to 1:

for i in range(10, 0, -1):
    print(i) 

Output:

10
9
8
7   
6
5
4
3
2
1

By setting step to -1, each loop iteration reduces i by 1 until we reach 1. Very useful for loops that depend on a particular number of iterations.

As you can probably tell, range() combined with for loops enormously simplifies automating calculations and repeating logic in Python.

For Loops with if Statements

Another common pattern is using conditional if statements inside for loops to add logic that executes under certain criteria per iteration.

For example, let‘s print only the even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6]

for n in numbers:
    if (n % 2 == 0):
        print(n)   

Output:

2
4 
6

We check each number with % to see if it has a remainder of 0 when divided by 2 (even) using the if statement. If so, we print. This allows selectively executing code per loop iteration.

Here is another example that searches for a specific value:

names = ["Alex", "John", "Mary", "Steve", "John"]  

for name in names:
    if (name == "John"):
        print("Found John!")
        break

Output:

Found John!

When we find John, we print a message and use break to terminate the loop since we are done searching.

You can also use continue to skip to the next iteration and pass as a placeholder with no operation.

Conditionals give you finer control over the logic executed during each loop iteration.

For Loops with Else Statements

In some cases, you may want to run a final block of code after the for loop finishes all iterations.

Python allows adding an optional else statement after the for loop to handle this.

The else block executes after the loop completes normally, but not if the loop terminated early from a break, exception etc.

Let‘s see an example:

fruits = ["apple", "banana", "cherry"]  

for fruit in fruits:  
    print(fruit)
else:
    print("Loop finished, no more fruits left!") 

Output:

apple
banana
cherry
Loop finished, no more fruits left!

Our else statement runs after looping through all the fruits since no break occurred beforehand.

This can be useful for closing files, final calculations, error handling, etc once the full sequence has been processed.

Nested For Loops

When dealing with multidimensional data, nested for loops are very useful for iterating through values in two dimensions.

The outer loop controls iterating through one sequence, while the nested inner loop processes each iteration of the outer sequencing again creating the nested effect.

Let‘s print a 2D grid of values using nested loops:

for i in range(3):
    for j in range(5):
        print(f"i={i}, j={j}") 

Output:

i=0, j=0
i=0, j=1 
i=0, j=2
i=0, j=3
i=0, j=4
i=1, j=0
i=1, j=1
...
i=2, j=4       

Our outer loop uses range(3) to repeat 3 times. The inner loop then iterates fully from 0 to 4 during each repetition of the outer loop.

This allows efficiently processing multi-dimensional data using the for loop‘s nesting capabilities.

Some examples of nested loops include:

  • Iterating through 2D lists/arrays
  • Looping through every pixel in an image
  • Generator/filter functions that process iterators

Iterating Over Dictionaries

In addition to lists and tuples, you‘ll often need to traverse dictionary keys or values.

Dicts don‘t maintain an order, but we can easily loop through contents with some methods.

To loop through keys, use the .keys() dictionary method:

person = {"name": "John", "age": 22, "job": "Designer"}

for key in person.keys():
    print(key)  

Output:

name
age
job

And to iterate over dictionary values, use .values():

for value in person.values():
    print(value)

Output:

John
22 
Designer

You can of course combine these techniques and use the key to retrieve associated values per iteration too.

This makes working with dictionaries much simpler.

Looping Over Strings

In some text processing cases, you may need to traverse strings on a character by character basis similar to lists.

We can do this easily with for loops by taking advantage of the fact that strings behave like sequences in Python.

Let‘s try editing a string by uppercasing all vowels:

vowels = "aeiou"
text = "This is a sample string"

for char in text:
    if char.lower() in vowels:
        print(char.upper(), end="")
    else: 
        print(char, end="")

Output:

ThIs Is A sAmPlE strIng

We loop through each character in the string with char, check if it‘s a vowel, then uppercase and print it if so.

The .lower() call makes comparison case-insensitive. print(char, end="") avoids new lines while iterating.

Being able to manipulate strings on a per character basis makes many text processing tasks much easier.

And that covers the main data types you‘ll want to iterate over with for loops!

Common For Loop Patterns

Let‘s discuss some common useful for loop patterns next:

Summation / Running Total

Use loop variables to build up a final value over iterations:

numbers = [1.5, 2, 3.3, 4]

total = 0
for num in numbers:
    total += num

print(total)    

Output:

10.8

Counting Occurrences

Use conditional logic to count matches:

text = "banana"
count = 0
for char in text:
    if (char == "a"): 
        count += 1

print(count)   

Output:

3

Filtering

Append matching values to a new list:

values = [1, 2, 3, 5, 7, 10]
evens= []

for num in values:
    if (num % 2 == 0):
        evens.append(num)

print(evens)

Output:

[2, 10]

These examples demonstrate some common patterns, but many more possibilities exist when leveraging Python‘s flexible for loops!

Best Practices

While for loops are very useful, some best practices should be kept in mind:

  • Avoid mutating the sequence inside the loop as it can cause unexpected behavior. Make a copy instead if needed.
  • Preallocate array variables if possible before loops with large numbers of iterations to avoid slow contiguous growth
  • Use loops alternatives like list comprehensions when simpler approach suffices
  • Watch out for off-by-one errors by printing the length and indices of sequences
  • Handle early termination logic correctly if using break or return statements
  • If performance is critical, compiles C extensions may be needed for numerical Python code instead of pure Python loops

Following best practices avoids common pitfalls and leads to more robust code.

Conclusion

We‘ve covered for loops extensively, including syntax, examples and tips for usage with all major Python data types. Some key takeaways:

  • For loops execute a code block repeatedly while processing a sequence
  • range(), lists and strings are common sequences to iterate over
  • Conditional logic like if/else alters control flow
  • Nested loops help navigate 2D data
  • Following best practices optimizes code

I hope you‘ve gained a thorough understanding of how to harness for loops for efficient data processing in Python. They are a crucial tool for automating repetitive tasks.

Let me know in the comments if you have any other for loop tips or questions!

Did you like those interesting facts?

Click on smiley face to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

      Interesting Facts
      Logo
      Login/Register access is temporary disabled