Python for‑in Loop: Full Guide from Basics to Comprehensions

目次

1. Introduction

What is the Python for in statement?

The Python for in statement is a syntax for looping over iterable data such as lists, dictionaries, and strings. In programming, there are many cases where you process elements of a list in order or perform repeated calculations. Using the for in statement lets you write concise and readable code. For example, a basic loop that retrieves each element of a list and processes it can be written as follows.
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
Output
apple
banana
cherry
Thus, using the for in statement allows you to extract list elements one by one and loop over them.

Intended Audience

This article is intended for readers such as:
  • Python beginners who want to learn the basics of the for in statement
  • Those who want to use for in to efficiently loop over lists, dictionaries, sets, etc.
  • People who want to master advanced techniques such as enumerate(), zip(), and list comprehensions

What You’ll Learn

By reading this article, you will understand and be able to apply the following:
  • The basic syntax and operation of the for in statement
  • How to use for in with lists, dictionaries, sets, and tuples
  • Loop control using <>break and continue
  • How to use and apply enumerate() and zip()
  • The mechanics and practical examples of the for-else construct
  • Writing efficient code with list comprehensions
We will thoroughly explain Python’s loop constructs with concrete code examples so you can understand and apply them effectively.

2. Basics of Python for in statement

What is a for in statement?

for in statement is one of the most commonly used constructs for looping in Python. It can extract elements from data types such as lists, dictionaries, tuples, strings, etc., in order, and repeat processing.

Basic syntax

for variable in iterable_object:
    process
  • variable: a variable that stores each element extracted within the loop
  • iterable_object: an iterable object such as a list, dictionary, tuple, set, string, etc.
  • process: the operation executed inside the loop

Basic usage example

When processing list elements in order, you can write as follows.
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
Output
apple
banana
cherry
Thus, each element of the list fruits is sequentially assigned to the variable fruit, and the loop’s processing is executed.

Role of the in operator

The Python in operator is used to check whether a specific element is contained in a list, dictionary, or string. Combined with a for loop, you can process each element of the data one by one.

Using the in operator with lists

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

if 3 in numbers:
    print("3 is in the list")
Output
3 is in the list

Using the in operator with dictionaries

For dictionaries (dict type), by default the in operator searches for keys.
person = {"name": "Alice", "age": 25, "city": "Tokyo"}

if "age" in person:
    print("age key exists")
Output
age key exists
Also, if you want to search for a dictionary’s value(s), use .values().
if 25 in person.values():
    print("value 25 exists")
Output
value 25 exists

Negative condition using not in

Using not in lets you specify a condition when an element does not exist.
if "email" not in person:
    print("email key does not exist")
Output
email key does not exist

Benefits of using the for in statement

The Python for in statement has the following advantages. ✅ Highly readable You can write simple and clear code when handling data such as lists or dictionaries. ✅ Less prone to out-of-range errors Since you don’t need to manage a counter variable like in a regular for loop, errors from exceeding array bounds are less likely. ✅ Easy handling of iterable data Applicable to various data structures such as lists, dictionaries, tuples, sets, strings, etc.

Summary

In this chapter, we learned the basics of the Python for in statement. Key points summary
  • for in statement is a construct for looping over iterable data such as lists or dictionaries
  • Using the in operator lets you easily check whether an element is present
  • Using not in allows you to set a condition for when an element is absent
  • Using the for in statement yields highly readable, simple code

3. Basic usage of the for in statement

Python’s for in statement is a handy tool for iterating over data structures such as lists, dictionaries, tuples, and sets. In this chapter, we will explain the basic usage of the for in statement in detail and present concrete code examples for each data type.

Looping over a list with for in

The list (list type) is one of the most commonly used data structures in Python. Using the for in statement allows you to process each element in a list sequentially.

Basic list looping

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

for fruit in fruits:
    print(fruit)
Output
apple
banana
cherry

How to get list indices (using enumerate())

A regular for in loop retrieves only the list elements, but if you also want to get the element indices, using the enumerate() function is convenient.
fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
Output
0: apple
1: banana
2: cherry

Looping over a dictionary (Dictionary)

A dictionary (dict type) is a data structure that stores key‑value pairs. You can use the for in statement to retrieve keys and values sequentially.

Looping over dictionary keys

By default, applying a for in statement to a dictionary retrieves only the keys.
person = {"name": "Alice", "age": 25, "city": "Tokyo"}

for key in person:
    print(key)
Output
name
age
city

Retrieving dictionary keys and values (using items())

If you want to retrieve not only the keys but also the values simultaneously, use the .items() method.
for key, value in person.items():
    print(f"{key}: {value}")
Output
name: Alice
age: 25
city: Tokyo

Looping over tuples and sets

Python’s for in statement can also be applied to tuples (tuple type) and sets (set type).

Looping over a tuple

A tuple is similar to a list but is an immutable data structure. You can loop over it with a for in statement just like a list.
colors = ("red", "green", "blue")

for color in colors:
    print(color)
Output
red
green
blue

Looping over a set

A set (set type) is a data structure that stores unique items. Since set elements have no guaranteed order, the iteration order may vary.
unique_numbers = {1, 2, 3, 4, 5}

for num in unique_numbers:
    print(num)
Output (order not guaranteed)
1
3
2
5
4

Looping over a string

Python strings (str type) can also be processed one character at a time using a for in statement.
word = "Python"

for char in word:
    print(char)
Output
P
y
t
h
o
n

Nested for loops (nested loops)

You can place a for loop inside another for loop. This is called a nested loop. For example, it can be used to process matrices (2‑dimensional lists).
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()  # newline
Output
1 2 3
4 5 6
7 8 9

Summary

In this chapter, we learned how to use the for in statement to loop over lists, dictionaries, tuples, sets, and strings. Key points
  • When looping over a list, using enumerate() also gives you the index
  • When looping over a dictionary, using .items() retrieves both keys and values
  • Tuples and sets can also be iterated with for in (though set order is not guaranteed)
  • Looping over a string lets you get one character at a time
  • Using nested for loops allows you to process multidimensional data (such as lists of lists)

4. Advanced Techniques Using for in

In addition to the basic usage of the for in statement that we’ve learned so far, Python offers various techniques to make the for in statement even more useful. In this chapter, we introduce advanced looping methods using functions such as range(), zip(), and enumerate().

Loop using range()

By using Python’s range() function, you can execute a loop over a specified range of numbers. range() can be treated like a list, but it is a memory-efficient iterable object.

Basic usage of range()

for i in range(5):
    print(i)
Output
0
1
2
3
4
By default, range(n) generates consecutive integers from 0 to n-1.

Specifying start, stop, and step values

You can specify the start value, stop value, and step (increment) using the range(start, stop, step) format.
for i in range(1, 10, 2):
    print(i)
Output
1
3
5
7
9

Looping in reverse using range()

Specifying a negative step value enables reverse looping.
for i in range(10, 0, -2):
    print(i)
Output
10
8
6
4
2

Simultaneous looping over multiple lists using zip()

When you want to loop over multiple lists simultaneously, the zip() function is handy.

Basic usage of zip()

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")
Output
Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old

When list lengths differ

If the lists have different lengths, zip() stops the loop at the shortest list.
names = ["Alice", "Bob"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")
Output
Alice is 25 years old
Bob is 30 years old

Getting indices using enumerate()

When you want to obtain the index (number) alongside list elements, enumerate() is useful.

Basic usage of enumerate()

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

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
Output
0: apple
1: banana
2: cherry

Specifying a start number

By providing a start number as the second argument to enumerate(), you can begin counting from any desired number.
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}: {fruit}")
Output
1: apple
2: banana
3: cherry

Using nested for loops

By nesting for loops, you can create double loops. For example, this is useful for processing matrices (2‑dimensional lists).

Processing a matrix using double loops

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

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()  # newline
Output
1 2 3
4 5 6
7 8 9

Looping over a sorted list using sorted()

If you want to loop while sorting a list, use sorted().
numbers = [5, 3, 8, 1, 2]

for num in sorted(numbers):
    print(num)
Output
1
2
3
5
8

Sorting in reverse (descending) order

for num in sorted(numbers, reverse=True):
    print(num)
Output
8
5
3
2
1

Summary

In this chapter, we introduced handy techniques for using the for in statement. Summary of key points
  • Using range() allows looping over a specified range of numbers
  • Specify range(start, stop, step) to control increment or decrement
  • Using zip() lets you loop over multiple lists simultaneously
  • Note that the loop ends at the shortest list
  • Using enumerate() enables looping with indices
  • You can set a start number with enumerate(list, start=number)
  • Using nested for loops allows processing multidimensional lists
  • Using sorted() lets you loop while sorting a list
By leveraging these techniques, you can achieve more flexible and efficient looping.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

5. for Loop Control

In Python’s for in statement, you can use break and continue control statements to finely control the loop’s operation. In this chapter, we will explain in detail the methods for controlling the flow of loops.

break and continue Differences

break and continue are control statements for interrupting or skipping loop processing.
Control StatementDescription
breakCompletely terminate the loop
continueSkip the processing of that iteration and move to the next loop

Using break to end a loop early

Using break allows you to forcefully terminate the loop at the point where a specified condition is met.
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        print("Found 3, ending loop")
        break
    print(num)
Output
1
2
Found 3, ending loop

Using continue to skip specific processing

Using continue skips the current processing of the loop and proceeds to the next iteration.
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        print("3 was skipped")
        continue
    print(num)
Output
1
2
3 was skipped
4
5

Using the for-else construct

Python’s for loops have a feature that allows you to add an else block to execute code when a specific condition does not occur.

Basic usage of for-else

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

for num in numbers:
    if num == 6:
        print("Found 6!")
        break
else:
    print("6 is not in the list")
Output
6 is not in the list
In this code, because 6 is not in the list, the for loop runs to completion and the else block is executed.

Using pass to do nothing

pass is used when a syntactic statement is required but there is no actual operation to perform.
for num in range(1, 6):
    if num == 3:
        pass  # do nothing
    else:
        print(num)
Output
1
2
4
5
In this code, when num == 3, no operation is performed and the loop proceeds to the next iteration.

Summary

In this chapter, we learned methods to control Python’s for in statement. Key Points Summary
  • break allows you to terminate the loop early
  • continue skips specific processing and moves to the next loop
  • for-else allows you to execute code only when the loop completes normally
  • pass is used when no operation is needed but a statement is required
By leveraging these control statements, flexible loop processing becomes possible.

6. List Comprehension

In Python, a concise way to generate lists using for loops is provided by list comprehensions (List Comprehension). Because they are often more readable than regular for loops and can improve performance, list comprehensions are a commonly used technique in Python.

What is a List Comprehension?

List comprehensions (List Comprehension) are syntax for creating lists concisely. Compared to generating lists with a regular for loop, you can write more compact code.

Basic Syntax

[expression for variable in iterable]
  • expression: the operation applied to each element (transformation, calculation, etc.)
  • variable: the element taken from the iterable object
  • iterable: an iterable object such as a list, dictionary, set, string, etc.

Creating a List Using a Regular for Loop

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

for num in numbers:
    squared_numbers.append(num ** 2)

print(squared_numbers)
Output
[1, 4, 9, 16, 25]

When Using a List Comprehension

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]

print(squared_numbers)
Output
[1, 4, 9, 16, 25]

Conditional List Comprehensions

In list comprehensions, adding if allows you to add only elements that meet a condition to the list.

Extracting Even Numbers Only

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers)
Output
[2, 4, 6]

Creating a List by Doubling Odd Numbers

numbers = [1, 2, 3, 4, 5, 6]
double_odd_numbers = [num * 2 for num in numbers if num % 2 == 1]

print(double_odd_numbers)
Output
[2, 6, 10]

List Comprehensions with if-else

List comprehensions can also use if-else to perform different operations based on a condition.

Odd Numbers Doubled, Even Numbers Unchanged

numbers = [1, 2, 3, 4, 5, 6]
modified_numbers = [num * 2 if num % 2 == 1 else num for num in numbers]

print(modified_numbers)
Output
[2, 2, 6, 4, 10, 6]

Nested List Comprehensions

List comprehensions also support nesting (nested structures), allowing you to write double loops concisely.

List Comprehension with a Double Loop

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]

print(flattened)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Dictionary Comprehension

Just like list comprehensions, dictionaries (dict) can also be generated using comprehension syntax.

Creating a Dictionary from a List

numbers = [1, 2, 3, 4, 5]
squared_dict = {num: num ** 2 for num in numbers}

print(squared_dict)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Summary

In this chapter, we learned the basics and applications of list comprehensions. Key Points
  • List comprehensions let you write simple list operations concisely
  • Using if lets you create conditional lists
  • Using if-else applies different operations based on a condition
  • Nested loops can also be written concisely with list comprehensions
  • Dictionary comprehensions are also possible

7. Frequently Asked Questions (FAQ)

Python’s for in statement is a simple and powerful construct, but there are many points where beginners can stumble. In this section, we present common questions and their solutions regarding the for in statement.

What is the difference between for in and while statements?

Python provides two loop constructs: the for in statement and the while statement.
Loop typeCharacteristics
for inFixed number of iterations
whileUntil a specific condition is met

Example of for in (fixed‑count loop)

for i in range(5):
    print(i)
Output
0
1
2
3
4
The for in statement is suitable when the number of iterations is known

Example of while (run until condition is met)

count = 0
while count < 5:
    print(count)
    count += 1
Output
0
1
2
3
4
The while statement is appropriate when you want to repeat until a condition is satisfied

Which data types can the in operator be used with?

The Python in operator can be used with the following iterable data types (objects that can be iterated over).
Data typeUse in for in statement
List (list)✅ Possible
Tuple (tuple)✅ Possible
Dictionary (dict)✅ Possible (keys are iterated)
Set (set)✅ Possible
String (str)✅ Possible

What is the difference between break and continue?

Control statementPurpose
breakEnds the loop completely
continueSkips the current iteration and proceeds to the next loop

When should you use the for-else construct?

for-else runs the else block only if the loop completes without encountering a break.

Basic usage of for-else

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

for num in numbers:
    if num == 6:
        print("Found 6!")
        break
else:
    print("6 is not in the list")
Output
6 is not in the list
Convenient for checking whether a specific element exists in a list

How to use a counter inside a for in loop

If you need to manage the loop counter manually, using enumerate() is convenient.

Using enumerate()

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

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
Using enumerate() eliminates the need to manage a counter variable explicitly

Causes and solutions when a for in loop does not work

Possible causes
  1. Not using an iterable object num = 10 for n in num: # TypeError print(n) Solution: num is an integer and not iterable. Use range(). for n in range(num): print(n)
  2. The list is empty python items = [] for item in items: print(item) # No output Solution: Verify that the list contains elements before iterating.

Summary

In this section, we introduced common questions about Python’s for in statement and their solutions. ✅ Key points
  • for and while difference: Use for for a fixed number of repetitions, and while for condition‑based repetitions
  • break ends the loop, continue skips the current iteration
  • for-else executes only if the loop finishes normally
  • Using enumerate() makes it easy to obtain the loop index

8. Summary

In this article, we covered Python’s for in statement from basics to advanced topics. In this section, we review what we’ve learned so far and organize the key points.

Basic for in Statement

  • The for in statement is a syntax for looping over iterable data such as lists, dictionaries, tuples, sets, and strings
  • Basic syntax for variable in iterable_object: # process
  • Looping over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

Advanced Techniques for for in

Loop using range()
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4
Loop over multiple lists simultaneously using zip()
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")
Get indices using enumerate()
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}: {fruit}")
Loop while sorting a list
numbers = [5, 3, 8, 1, 2]
for num in sorted(numbers):
    print(num)

Controlling Loops

Terminate a loop early with break
for num in range(1, 6):
    if num == 3:
        break
    print(num)
Skip specific iterations with continue
for num in range(1, 6):
    if num == 3:
        continue
    print(num)
Utilize for-else
for num in range(1, 6):
    if num == 7:
        break
else:
    print("7 was not found")

Looping with List Comprehensions

Standard for loop
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
    squared_numbers.append(num ** 2)
Write concisely with list comprehensions
squared_numbers = [num ** 2 for num in numbers]
Conditional list comprehensions
even_numbers = [num for num in numbers if num % 2 == 0]
Dictionary comprehensions
squared_dict = {num: num ** 2 for num in numbers}

Common Errors and Solutions for for in Statements

Integers cannot be iterated directly
num = 10
for i in num:  # error
    print(i)
Solution
for i in range(num):
    print(i)
The in operator on dictionaries checks keys by default
person = {"name": "Alice", "age": 25}
if "Alice" in person:  # returns False because it searches keys
    print("Exists")
Solution: Use .values() when you want to check values
if "Alice" in person.values():
    print("Exists")

Resources for Further Learning

To deepen your understanding of Python’s for in statement, refer to the following resources.

Summary and Future Learning Points

In this article, we covered Python’s for in statement from basics to advanced topics, control methods, list comprehensions, and common questions. ✅ Understanding the for in statement makes basic data processing in Python smoother!Using list comprehensions, zip(), and enumerate() lets you write more efficient code!Master control structures like break, continue, and for-else to avoid errors! For future study, learning advanced looping constructs such as while loops, recursive functions, and generators (yield) will deepen your understanding of Python. Leverage Python’s looping constructs to write efficient and readable code!