Skip to content

For Loops In Python: A Complete Guide With Examples

For loops are an integral element of programming in Python and many other languages. They allow you to iterate through sequences like lists, tuples, and dictionaries to perform repeated actions efficiently.

In this comprehensive guide, we’ll start from the basics of what for loops in Python are before exploring syntax, real-world use cases, best practices when using them, and more.

What Are For Loops in Python?

A for loop enables you to execute a block of code multiple times. With each iteration, the loop cycles through the sequence it is iterating over.

Here is the basic syntax of a for loop in Python:

for element in sequence:
    # code to execute

Some key points about the syntax:

  • element: The variable that gets assigned to the current value in the sequence on every iteration
  • sequence: The sequence to iterate over. This could be a list, tuple, dictionary, string etc.
  • #code to execute: The code block to run on every pass of the loop

Conceptually, you can think of the process happening as:

  1. On the first pass, element gets assigned to the first value in sequence
  2. The code block executes using this value
  3. On the second pass, element gets reassigned to the second value in sequence
  4. The code block runs again with the new value

This continues until the last element in sequence has been assigned to element.

The key benefit here is reducing repetitive code. We can perform the same code block over an entire sequence by iterating through it instead of writing the block out separately for each element.

A Brief History of For Loops

The concepts of loops and iteration in programming languages originated in the 1950s and 1960s.

FORTRAN (Formula Translation) is credited as the first high-level language to implement for loops. Developed in 1954-1957, FORTRAN had a DO statement allowing repetitive execution of code.

Over time, other languages included their own versions of for loops or iterative loops. When C was created in 1972, it expanded for loops with more flexibility through the for keyword.

Guido van Rossum included for loops in his creation of Python in 1991. They continue to be a cornerstone of iteration in the language today.

Now, let‘s look at some examples of using for loops in Python.

For Loops in Action: Basic Examples

Let‘s start with a simple example of iterating through a list of fruits.

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

for fruit in fruits:
   print(fruit)

Output:

apple
banana  
cherry

Here‘s an explanation of what happens:

  1. fruits contains the sequence to iterate over
  2. On the first pass of the loop, fruit gets assigned to "apple"
  3. fruit gets printed
  4. On the second pass, fruit gets reassigned to "banana"
  5. fruit gets printed again
  6. This continues to "cherry", printing each fruit

The power here is that we can perform the print(fruit) action on each element without having to call print for each one individually.

Let‘s look at another example:

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for digit in digits:
   print(digit, ":", digit * 3) 

Output:

0 : 0
1 : 3 
2 : 6
3 : 9
4 : 12
5 : 15
6 : 18 
7 : 21
8 : 24
9 : 27

This demonstrates performing an additional action on each element by printing the digit multiplied by 3.

The key thing to observe again is how we can easily execute code for every item in digits through the for loop without explicitly writing 10 print statements.

Iterating Over Different Data Types

So far, our examples iterated over a list. But many other data types can be looped through using for loops:

Lists

Lists are a very common type used in for loops:

colors = ["red", "blue", "green"] 

for color in colors:
  print(color)

Strings

We can iterate through each character in a string:

for char in "python":
   print(char) 

Output:

p
y    
t
h
o
n

Tuples

Tuples work the same way as lists:

digits = (0, 1, 2)  

for digit in digits:
   print(digit)

Dictionaries

When looping through dictionaries, element gets assigned to each key in the dictionary on each pass:

squares = {1: 1, 2: 4, 3: "error", 4: 16,}  

for key in squares:
    print(squares[key])

Output:

1 
4
error
16

Here we used key to index into the dictionary on each pass and print the value.

This demonstrates the flexibility of iterating through different data types. Wherever we have an iterable sequence, we can leverage for loops to traverse it.

Using range() and len()

We often want to iterate up to a certain number of times rather than over a predefined sequence.

The range() function allows us to specify a start number, end number, and optional step size to iterate through. len() returns the length of something.

Let‘s print the numbers 0 to 9 without explicitly writing out the sequence:

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

We can also provide a start, stop, and step size. This would print the even numbers from 0 to 20:

for i in range(0, 21, 2):   
  print(i)   

Output:

0 
2
4 
6
8
10
12
14
16
18
20

The len() function is commonly used with data structures we cannot use range() with directly:

colors = ["red", "blue", "green"]  

for i in range(len(colors)):
  print(i, colors[i])

The major reasons to use range() and len() are:

  • Not needing to define explicit sequences to iterate through
  • More flexibility and programmatic control flow based on start, stop, step values

Make note of how powerful these tools are within for loops!

Controlling Loop Execution

We often need finer-grained control of our loops besides just running A to Z. Several statements help us achieve this.

Break

break terminates the loop immediately without running the remaining iterations.

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for d in digits:
  if d == 5: 
    break

  print(d) 

Output:

0
1  
2
3
4

Execution stops once d == 5 triggers the break.

Continue

continue skips the current iteration, jumps to the update statement, and resumes on the next pass.

for x in range(10):
  if x % 2 == 0:
    continue

  print(x)

Output:

1
3
5
7
9

Here even values get skipped by continue.

Else

An optional else after the loop runs once when the full sequence completes.

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

for fruit in fruits:
  if fruit == "lemon":
    found = True 
    break

if not found: 
  print("lemon not found")

Output:

lemon not found

These statements give precise control over when code runs, improving efficiency and readability.

Nested For Loops

Nesting means putting a loop inside another loop. The inner loop runs to completion for every iteration of the outer loop.

Here‘s a basic example:

rows = range(3)
cols = range(5)

for r in rows:
  for c in cols:
    print(f"Row: {r} Col: {c}") 

Output:

Row: 0 Col: 0   
Row: 0 Col: 1
Row: 0 Col: 2
Row: 0 Col: 3  
Row: 0 Col: 4 
Row: 1 Col: 0 
...
Row: 2 Col: 3
Row: 2 Col: 4

This prints 15 combinations of rows 0-2 and columns 0-4. The inner loop runs fully inside each outer iteration.

Nested loops are used in programming concepts like matrices, combinatorics problems, GUI table/grid layouts etc. Being comfortable with them expands your coding horizons!

Common "Gotchas"

Here are two tricky situations to watch out for regarding for loops:

Mutating lists

Indexing into a list while iterating through it leads to potential unexpected behavior or errors if indices get shifted. Copy the list first before making changes:

values = [1, 2, 3]
copy = values[:]  

for v in copy:  
  values.remove(v)   

Infinite loops

Forgetting an incrementing statement can lead to endless loops:

i = 0
for element in sequence: 
  print(element) # infinite iterations! 

Adding i += 1 fixes this.

Stay cognizant of these issues when writing loops!

For Loops vs While Loops

The for loop shines in situations where:

  • We need to execute code over an existing sequence
  • We know how many iterations are needed

But what about repeating code an unknown number of times until a condition changes? Enter while loops.

counter = 0 

while counter < 10:
   print("Counter: ", counter)
   counter += 1

while keeps looping until counter >= 10. Useful when we want code running until hitting a particular target state.

Some coders lean more on for loops, others on while loops. Mastering both will serve you well!

Conclusion

For loops enable powerful, efficient iteration in Python. We can traverse sequences like lists and strings element-by-element to execute code without repetitive blocks. Statements like break, continue and else grant further runtime control.

Learning to leverage for loops fully unlocks greater programming capabilities in data analysis, numerical processing, file I/O iterations and more. Use this guide as your reference taking the next steps mastering for loops within your own projects!