目次
- 1 1. Introduction
- 2 2. Basics of Python for in statement
- 3 3. Basic usage of the for in statement
- 4 4. Advanced Techniques Using for in
- 5 5. for Loop Control
- 6 6. List Comprehension
- 7 7. Frequently Asked Questions (FAQ)
- 7.1 What is the difference between for in and while statements?
- 7.2 Which data types can the in operator be used with?
- 7.3 What is the difference between break and continue?
- 7.4 When should you use the for-else construct?
- 7.5 How to use a counter inside a for in loop
- 7.6 Causes and solutions when a for in loop does not work
- 7.7 Summary
- 8 8. Summary
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)Outputapple
banana
cherryThus, 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 instatement - Those who want to use
for into 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 instatement - How to use
for inwith lists, dictionaries, sets, and tuples - Loop control using <>break and
continue - How to use and apply
enumerate()andzip() - The mechanics and practical examples of the
for-elseconstruct - Writing efficient code with list comprehensions
Ad
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:
processvariable: a variable that stores each element extracted within the loopiterable_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)Outputapple
banana
cherryThus, 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")Output3 is in the listUsing 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")Outputage key existsAlso, if you want to search for a dictionary’s value(s), use .values().if 25 in person.values():
print("value 25 exists")Outputvalue 25 existsNegative 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")Outputemail key does not existBenefits 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 Pythonfor in statement. Key points summaryfor instatement is a construct for looping over iterable data such as lists or dictionaries- Using the
inoperator lets you easily check whether an element is present - Using
not inallows you to set a condition for when an element is absent - Using the
for instatement 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)Outputapple
banana
cherryHow 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}")Output0: apple
1: banana
2: cherryLooping 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 afor in statement to a dictionary retrieves only the keys.person = {"name": "Alice", "age": 25, "city": "Tokyo"}
for key in person:
print(key)Outputname
age
cityRetrieving 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}")Outputname: Alice
age: 25
city: TokyoLooping over tuples and sets
Python’sfor 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 afor in statement just like a list.colors = ("red", "green", "blue")
for color in colors:
print(color)Outputred
green
blueLooping 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
4Looping 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)OutputP
y
t
h
o
nNested 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() # newlineOutput1 2 3
4 5 6
7 8 9Summary
In this chapter, we learned how to use thefor 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
forloops allows you to process multidimensional data (such as lists of lists)
Ad
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)Output0
1
2
3
4By 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 therange(start, stop, step) format.for i in range(1, 10, 2):
print(i)Output1
3
5
7
9Looping in reverse using range()
Specifying a negative step value enables reverse looping.for i in range(10, 0, -2):
print(i)Output10
8
6
4
2Simultaneous 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")OutputAlice is 25 years old
Bob is 30 years old
Charlie is 35 years oldWhen 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")OutputAlice is 25 years old
Bob is 30 years oldGetting 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}")Output0: apple
1: banana
2: cherrySpecifying a start number
By providing a start number as the second argument toenumerate(), you can begin counting from any desired number.for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")Output1: apple
2: banana
3: cherryUsing 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() # newlineOutput1 2 3
4 5 6
7 8 9Looping 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)Output1
2
3
5
8Sorting in reverse (descending) order
for num in sorted(numbers, reverse=True):
print(num)Output8
5
3
2
1Summary
In this chapter, we introduced handy techniques for using thefor 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
forloops allows processing multidimensional lists - Using
sorted()lets you loop while sorting a list

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 Statement | Description |
|---|---|
break | Completely terminate the loop |
continue | Skip 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)Output1
2
Found 3, ending loopUsing 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)Output1
2
3 was skipped
4
5Using 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")Output6 is not in the listIn 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)Output1
2
4
5In 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’sfor in statement. Key Points Summarybreakallows you to terminate the loop earlycontinueskips specific processing and moves to the next loopfor-elseallows you to execute code only when the loop completes normallypassis used when no operation is needed but a statement is required
Ad
6. List Comprehension
In Python, a concise way to generate lists usingfor 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 regularfor 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 objectiterable: 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, addingif 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
iflets you create conditional lists - Using
if-elseapplies different operations based on a condition - Nested loops can also be written concisely with list comprehensions
- Dictionary comprehensions are also possible
Ad
7. Frequently Asked Questions (FAQ)
Python’sfor 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 type | Characteristics |
|---|---|
for in | Fixed number of iterations |
while | Until a specific condition is met |
Example of for in (fixed‑count loop)
for i in range(5):
print(i)Output0
1
2
3
4✅ The for in statement is suitable when the number of iterations is knownExample of while (run until condition is met)
count = 0
while count < 5:
print(count)
count += 1Output0
1
2
3
4✅ The while statement is appropriate when you want to repeat until a condition is satisfiedWhich 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 type | Use 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 statement | Purpose |
|---|---|
break | Ends the loop completely |
continue | Skips 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")Output6 is not in the list✅ Convenient for checking whether a specific element exists in a listHow 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 explicitlyCauses and solutions when a for in loop does not work
✅ Possible causes- Not using an iterable object
num = 10 for n in num: # TypeError print(n)Solution:numis an integer and not iterable. Userange().for n in range(num): print(n) - The list is empty
python items = [] for item in items: print(item) # No outputSolution: Verify that the list contains elements before iterating.
Summary
In this section, we introduced common questions about Python’sfor in statement and their solutions.
✅ Key pointsforandwhiledifference: Useforfor a fixed number of repetitions, andwhilefor condition‑based repetitionsbreakends the loop,continueskips the current iterationfor-elseexecutes only if the loop finishes normally- Using
enumerate()makes it easy to obtain the loop index
Ad
8. Summary
In this article, we covered Python’sfor 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 instatement 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 listnumbers = [5, 3, 8, 1, 2]
for num in sorted(numbers):
print(num)Controlling Loops
✅ Terminate a loop early withbreakfor num in range(1, 6):
if num == 3:
break
print(num)✅ Skip specific iterations with continuefor num in range(1, 6):
if num == 3:
continue
print(num)✅ Utilize for-elsefor num in range(1, 6):
if num == 7:
break
else:
print("7 was not found")Looping with List Comprehensions
✅ Standardfor loopnumbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
squared_numbers.append(num ** 2)✅ Write concisely with list comprehensionssquared_numbers = [num ** 2 for num in numbers]✅ Conditional list comprehensionseven_numbers = [num for num in numbers if num % 2 == 0]✅ Dictionary comprehensionssquared_dict = {num: num ** 2 for num in numbers}Common Errors and Solutions for for in Statements
✅ Integers cannot be iterated directlynum = 10
for i in num: # error
print(i)➡ Solutionfor i in range(num):
print(i)✅ The in operator on dictionaries checks keys by defaultperson = {"name": "Alice", "age": 25}
if "Alice" in person: # returns False because it searches keys
print("Exists")➡ Solution: Use .values() when you want to check valuesif "Alice" in person.values():
print("Exists")Resources for Further Learning
To deepen your understanding of Python’sfor in statement, refer to the following resources.- Official Python Documentation https://docs.python.org/3/tutorial/controlflow.html
- Online Python practice sites
- LeetCode (Python problem set)
- AtCoder (competitive programming)
Summary and Future Learning Points
In this article, we covered Python’sfor 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!



