Python Iteration Guide: From For Loops to itertools

目次

1. Introduction

Python iteration is an essential element for improving program efficiency and readability. Most programming languages have a loop structure called foreach, which allows easy iteration over each element of a sequence, but Python does not have a direct foreach loop. Therefore, Python uses various features such as for loops, enumerate, and zip to achieve similar processing. This article explains how to perform iteration in Python that corresponds to foreach, from a simple and practical perspective.

Why doesn’t Python have foreach?

Python does not explicitly adopt foreach because the language design emphasizes simplicity and flexibility. for loops and comprehensions are designed to make many iterative tasks easy to implement. Python provides robust features for iterating over indices and multiple sequences simultaneously, so even without foreach, similar expressions are possible.

Benefits of Iteration in Python

Iteration in Python offers the following advantages.
  • Conciseness: Code can be written more concisely than in other languages, resulting in higher readability.
  • Flexibility: Uniform iteration is possible across multiple sequences and different data structures.
  • Comprehensions: List, dictionary, and other collections can be generated simply, making it easy to write efficient code.
In the next chapter, we will look in detail at the basic usage of the for loop as a fundamental aspect of iteration in Python.

2. Basics of for loops in Python

The for loop, a core iteration feature in Python, is frequently used to process each element of a sequence. Here we provide a detailed explanation of the basic usage of for loops for sequences like lists and tuples.

Basic syntax of for loops

A Python for loop is written using the following syntax:
for element in sequence:
    process
  • Element: The variable that receives each item of the sequence in order during each iteration.
  • Sequence: An iterable data structure such as a list, tuple, or string.

Example 1: Iterating over a list

First, let’s look at a basic for loop example using a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
In the code above, each element of the fruits list is assigned in order to fruit, and print(fruit) is executed. This example yields the following output.
apple
banana
cherry

Example 2: Iterating over a string

Strings are also sequences, so you can iterate over each character.
text = "hello"
for char in text:
    print(char)
In this code, each character of the string text is assigned in order to char and printed. The result is as follows.
h
e
l
l
o

Example 3: Iterating over a specified range (range function)

If you want to iterate over a specified range of numbers, use the range() function.
for i in range(5):
    print(i)
This code assigns the values 0 through 4 in order to i and prints them.
0
1
2
3
4

How to use the range function

  • range(n): Generate numbers from 0 up to n-1.
  • range(start, stop): Generate numbers from start to stop-1.
  • range(start, stop, step): Generate numbers from start to stop-1 with a step of step.

Practical examples of for loops

Calculating the sum of an array

Here’s an example using a for loop to calculate the sum of the numbers in a list.
numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
    total += number
print("Total:", total)
In this code, the numbers in the list are added to total in order, and the final total is printed.

Conditional processing of elements

You can also set conditions inside a for loop to process elements based on certain conditions.
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")
This code determines whether each number is even or odd and prints the result.

Nested for loops (nested structure)

for loops can be nested, which is useful when processing multiple lists or two-dimensional lists.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for item in row:
        print(item, end=" ")
    print()  # newline
This code displays all elements of a two-dimensional list (a list of lists).
1 2 3
4 5 6
7 8 9

Summary

Python’s for loop is a fundamental construct for efficiently iterating over sequences such as lists, tuples, and strings. By combining the range() function with conditionals and nesting, you can implement a variety of processes simply. Understanding this basic structure allows you to perform flexible iteration comparable to foreach.

3. Using the enumerate function

When iterating over a sequence in Python, there are times when you want to obtain both the list index and the element simultaneously. In such cases, using the enumerate function allows you to efficiently retrieve the index and element while looping. Here, we will explain in detail the basic usage and practical examples of the enumerate function.

Basic syntax of the enumerate function

By using the enumerate function, each element in the sequence is assigned an index, generating pairs of index and element. It is used with the following syntax.
for index, element in enumerate(sequence):
    process
  • Index: the index number corresponding to each element in the sequence.
  • Element: each element in the sequence.
  • Sequence: an iterable data structure such as a list, tuple, or string.

Example 1: Getting list indices and elements simultaneously

An example that processes a list by obtaining its indices and elements simultaneously using enumerate.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
This code outputs each element in the fruits list along with its index.
0: apple
1: banana
2: cherry

Example 2: Specifying a start index

The enumerate function has an option to specify a start index. By default, indices start at 0, but you can set any value as the start index.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}: {fruit}")
This code outputs indices starting from 1.
1: apple
2: banana
3: cherry

Practical examples of the enumerate function

Displaying task list progress

The enumerate function can also be useful when indexes are helpful, such as in task management. The example below displays the progress of each task in a list format.
tasks = ["Laundry", "Cleaning", "Cooking"]
for index, task in enumerate(tasks, start=1):
    print(f"Task{index}: {task} - Completed")
This code outputs each task in the task list with a number.
Task1: Laundry - Completed
Task2: Cleaning - Completed
Task3: Cooking - Completed

Processing based on specific conditions within an array

When you want to process elements at specific positions in an array using their indices, enumerate is also handy.
numbers = [10, 20, 30, 40, 50]
for index, number in enumerate(numbers):
    if index % 2 == 0:
        print(f"Element {number} at index {index} has an even index")
This code outputs the elements located at even indices.
Element 10 at index 0 has an even index
Element 30 at index 2 has an even index
Element 50 at index 4 has an even index

Summary

The enumerate function is extremely useful for obtaining indices and elements simultaneously. Because you can specify a start index, it is suitable for numbering lists and processing based on specific conditions. In particular, it makes it easier to track each element in a list, improving code readability and maintainability.

4. Simultaneous Iteration of Multiple Sequences with the zip Function

Using Python’s zip function, you can iterate over multiple sequences simultaneously. This feature is very useful when you want to process lists, tuples, or other sequences in parallel. Here we introduce the basic usage and practical examples of the zip function.

Basic Syntax of the zip Function

The zip function takes multiple sequences as arguments, groups their elements into tuples, and produces an iterable object. Use the zip function with the following syntax.
for element1, element2, ... in zip(sequence1, sequence2, ...):
    process
  • element1, element2…: One element from each sequence is grouped into a tuple and assigned to variables in order.
  • sequence1, sequence2…: Specify the sequences you want to process together, such as lists or tuples.

Example 1: Iterating Over Two Lists Simultaneously

This example iterates over two lists simultaneously using the zip function and prints combined elements from each list.
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
    print(f"{name}'s score is {score}")
This code iterates over the names list and the scores list at the same time, outputting names and scores.
Alice's score is 85
Bob's score is 92
Charlie's score is 78

Example 2: Iterating Over Three or More Lists Simultaneously

The zip function also supports three or more sequences, so you can process multiple lists or tuples at once.
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
grades = ["B", "A", "C"]
for name, score, grade in zip(names, scores, grades):
    print(f"{name}'s score is {score}, and the grade is {grade}")
This code outputs names, scores, and grades together.
Alice's score is 85, and the grade is B
Bob's score is 92, and the grade is A
Charlie's score is 78, and the grade is C

Behavior of the zip Function When Sequences Have Different Lengths

When using the zip function, if the sequences have different lengths, iteration stops at the length of the shortest sequence. Let’s check this in the example below.
names = ["Alice", "Bob"]
scores = [85, 92, 78]  # 3 elements
for name, score in zip(names, scores):
    print(f"{name}'s score is {score}")
In this case, since names has only two elements, the third element is ignored and the output will be as follows.
Alice's score is 85
Bob's score is 92

Practical Examples of the zip Function

Displaying List Elements as Pairs

Using the zip function, you can also pair adjacent elements within a single list for processing.
data = [10, 20, 30, 40]
for x, y in zip(data, data[1:]):
    print(f"Pair: ({x}, {y})")
This code pairs adjacent elements and prints them.
Pair: (10, 20)
Pair: (20, 30)
Pair: (30, 40)

Summary

The zip function is a powerful tool for iterating over multiple sequences at the same time. It helps with tasks like pairing or combining different pieces of data and allows you to write concise code. When working with sequences of different lengths, using zip_longest as needed enables flexible iteration.
年収訴求

5. List Comprehensions (List Comprehension)

Python includes a powerful technique called “list comprehension” for generating sequences simply. By using list comprehensions, generating lists with the traditional for loop becomes even more concise and readable. This chapter explains the basic usage of list comprehensions, along with real code examples, to illustrate their convenience.

Basic Syntax of List Comprehensions

List comprehensions are written using the following syntax.
[expression for element in sequence]
  • Expression: The operation applied to each element.
  • Element: The variable that receives each item from the sequence in order.
  • Sequence: An iterable data structure such as a list, tuple, or string.

Example 1: Basic List Comprehension

For example, to create a new list by doubling each element in a list, using the traditional for loop would be written as follows.
numbers = [1, 2, 3, 4, 5]
doubled = []
for number in numbers:
    doubled.append(number * 2)
print(doubled)
Using a list comprehension, the above code can be written concisely as follows.
numbers = [1, 2, 3, 4, 5]
doubled = [number * 2 for number in numbers]
print(doubled)
The output is as follows.
[2, 4, 6, 8, 10]

Conditional List Comprehensions

In list comprehensions, you can add a conditional expression to process only specific elements. The condition is written as for followed by if.

Example 2: Conditional List Comprehension

For instance, to double only the even numbers in a list, you would write:
numbers = [1, 2, 3, 4, 5]
doubled_even = [number * 2 for number in numbers if number % 2 == 0]
print(doubled_even)
This code extracts only the even numbers and creates a new list with them doubled.
[4, 8]

Example 3: Conditional List Comprehension Using else

If you want to apply different processing to each element using conditional branching, you can add else before if.
numbers = [1, 2, 3, 4, 5]
result = [number * 2 if number % 2 == 0 else number for number in numbers]
print(result)
This code doubles the number when it is even, and otherwise adds the original number to the list.
[1, 4, 3, 8, 5]

Summary

By leveraging list comprehensions, you can generate lists more concise and efficiently compared to for loops. Combining simple conditional processing and specific operations lets you write more Pythonic code. However, complex comprehensions can reduce readability, so it’s important to use them in appropriate situations.

6. Iterating Over Dictionaries

A dictionary (dict) is one of the primary data structures in Python, used to store key‑value pairs. Like lists and tuples, dictionaries can be iterated over, but with dictionaries you often retrieve keys, values, or both. This chapter explains how to iterate over dictionaries and useful functions in detail.

Basic Dictionary Iteration

In basic dictionary iteration, you use a for loop to obtain either keys, values, or key‑value pairs.

Example 1: Iterating Over Keys Only

When you iterate over a dictionary with a for loop, it yields only the keys by default.
person = {"name": "Taro", "age": 30, "occupation": "Engineer"}
for key in person:
    print(key)
This code prints all the dictionary’s keys in order.
name
age
occupation

Example 2: Iterating Over Values Only

To iterate over a dictionary’s values, use the values() method.
person = {"name": "Taro", "age": 30, "occupation": "Engineer"}
for value in person.values():
    print(value)
This code prints all the dictionary’s values in order.
Taro
30
Engineer

Example 3: Iterating Over Key‑Value Pairs

If you want to retrieve both keys and values simultaneously, use the items() method. This returns each pair as a tuple, which can be unpacked into two variables.
person = {"name": "Taro", "age": 30, "occupation": "Engineer"}
for key, value in person.items():
    print(f"{key}: {value}")
This code prints all the key‑value pairs.
name: Taro
age: 30
occupation: Engineer

Conditional Dictionary Iteration

If you want to retrieve only the pairs that meet a specific condition within a dictionary, you can specify the condition using a if statement.

Example 4: Outputting Only Pairs with Specific Values

For example, to output only items where the age is 30 or higher, you would write:
people = {"Taro": 30, "Hanako": 25, "Jiro": 35}
for name, age in people.items():
    if age >= 30:
        print(f"{name} is at least 30 years old")
This code outputs only the pairs that satisfy the condition.
Taro is at least 30 years old
Jiro is at least 30 years old

Dictionary Comprehensions

Just like list comprehensions, dictionary comprehensions are also possible. They allow you to create a new dictionary based on a condition.

Example 5: Creating a New Dictionary with a Condition

For instance, to create a new dictionary that includes only people aged 30 or older, you can write:
people = {"Taro": 30, "Hanako": 25, "Jiro": 35}
adults = {name: age for name, age in people.items() if age >= 30}
print(adults)
The output of this code is as follows.
{'Taro': 30, 'Jiro': 35}

Summary

In Python, you can iterate over dictionaries by retrieving keys, values, or key‑value pairs. Additionally, conditional dictionary comprehensions and handling nested dictionaries enable flexible data processing. Dictionaries are a very handy data structure for organizing and managing complex data, and using the appropriate iteration techniques enhances their usefulness.

7. Iterating Over Sets

A set (set) is a data structure that stores unique elements, useful for checking whether a particular element is present or removing duplicates from a list. Because Python sets are unordered, unlike lists or tuples you cannot access elements by index, but you can iterate over all elements using a for loop. In this chapter, we’ll cover the basics of iterating over sets, conditional iteration, and iteration methods that involve set-specific operations.

Basic Set Iteration

To process every element in a set, use a for loop. Because sets have no order, the order of processing may differ each time.

Example 1: Print All Elements of a Set

First, let’s look at a basic iteration example that prints every element in a set.
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
    print(fruit)
The output order is not guaranteed, but each element appears only once.
banana
cherry
apple

Conditional Set Iteration

You can also process set elements that meet specific conditions. Use a if statement to filter based on a condition.

Example 2: Print Only Elements That Satisfy a Condition

For instance, to output only strings in the set that are at least five characters long, you would write:
fruits = {"apple", "banana", "cherry", "fig", "kiwi"}
for fruit in fruits:
    if len(fruit) >= 5:
        print(fruit)
This code prints fruit names with five or more characters.
banana
cherry
apple

Set Comprehensions

Like list comprehensions, set comprehensions are also available. Using a set comprehension lets you concisely create a new set based on a condition.

Example 3: Create a New Set with a Condition

For example, to create a new set that contains only elements with five or more characters, as in the previous example, you can write:
fruits = {"apple", "banana", "cherry", "fig", "kiwi"}
long_fruits = {fruit for fruit in fruits if len(fruit) >= 5}
print(long_fruits)
The output will look like the following (order is not guaranteed).
{'banana', 'cherry', 'apple'}

Summary

Sets are a data structure that disallows duplicates and has no order, giving them characteristics different from lists or tuples. They are especially suited for handling unique data and for operations with other sets to find intersections or differences. Additionally, using set comprehensions enables concise and efficient data processing.

8. Using the itertools Module

itertools module is a handy toolkit included in the Python standard library to assist with iteration. It provides many functions for efficiently handling iterable data structures, which is especially useful when working with large amounts of data. In this chapter, we explain the main functions of the itertools module and how to use them.

Key Functions of the itertools Module

The itertools module provides a variety of functions to enhance iteration. Here we introduce representative functions and explain how to use them with concrete examples.

1. count function

The count function is an iterator that generates numbers increasing infinitely from a specified start value. It is mainly used for generating sequential numbers when no upper limit is set.
from itertools import count

for i in count(10):
    if i > 15:
        break
    print(i)
This code starts at 10 and outputs integers less than 16.
10
11
12
13
14
15

2. cycle function

The cycle function creates an iterator that repeats a given sequence infinitely. It is useful when you want to output a specific pattern repeatedly.
from itertools import cycle

count = 0
for item in cycle(["A", "B", "C"]):
    if count == 6:
        break
    print(item)
    count += 1
This code repeats “A”, “B”, “C” and outputs them a total of 6 times.
A
B
C
A
B
C

3. repeat function

The repeat function creates an iterator that repeats a specified element infinitely. You can also specify the number of repetitions with a second argument.
from itertools import repeat

for item in repeat("Python", 3):
    print(item)
This code outputs “Python” three times.
Python
Python
Python

4. accumulate function

The accumulate function creates an iterator that computes the cumulative sum of a given sequence. For example, it is handy for adding list elements sequentially. By using a custom function, you can also perform other calculations such as products or maximum values.
from itertools import accumulate

numbers = [1, 2, 3, 4, 5]
result = list(accumulate(numbers))
print(result)
This code calculates the cumulative sum of a list and outputs the following.
[1, 3, 6, 10, 15]

Summary

The itertools module offers a wealth of functions for efficiently implementing complex iteration. It is especially useful when you need infinite iteration or combinations and permutations of data, helping to keep code concise and speed up processing. By handling iteration more flexibly, you can write Python code that handles large datasets and complex operations.

9. Summary

Python offers various ways to handle iteration, each with its own characteristics and uses. Throughout this series, we learned diverse techniques to make iteration in Python more efficient. In this chapter, we’ll review those techniques so you can choose the right option for your goals.

Key Points and Uses of Each Method

Below is a concise summary of the key points and uses of each method.

1. for Loop

Point: The basic iteration syntax in Python. Simple and versatile. Use: Used when processing sequences such as lists, tuples, or strings.

2. enumerate Function

Point: A function for obtaining both the index and the element simultaneously. Use: Iterating over data where order matters or when an index is needed.

3. zip Function

Point: Allows simultaneous iteration over multiple sequences. Use: Convenient for processing corresponding elements of different lists or tuples.

4. List Comprehension

Point: A simple and efficient way to generate lists. Conditional processing is also possible. Use: Generating and filtering lists based on conditions or expressions.

5. Dictionary Iteration

Point: Can retrieve keys, values, or key-value pairs. Use: Used when handling dictionary data and processing based on keys and values.

6. Set Iteration

Point: Can process data with unique (non-duplicate) elements. Use: Processing unique data and performing operations with other sets.

7. itertools Module

Point: Enables infinite iteration, combinations of multiple sequences, and generation of permutations and combinations. Use: For complex iteration or when efficiently handling large amounts of data.

Guidelines for Choosing the Optimal Method

In iteration, it’s important to select the optimal method based on the goal and data structure. Below are guidelines for choosing the appropriate iteration technique for each purpose.
  1. Simple list or tuple iteration: The basic for loop is the most straightforward and simple.
  2. When an index is needed: By using enumerate, you can loop while obtaining both the index and the element simultaneously.
  3. When processing multiple sequences simultaneously: Using zip allows you to efficiently process multiple lists or tuples in parallel.
  4. Conditional list generation: Using list comprehensions lets you select elements conditionally and store computed results directly in a list.
  5. When special operations on dictionaries or sets are needed: By using items(), values() methods, or set comprehensions specialized for dictionaries and sets, you can easily handle keys and values or unique data.
  6. When advanced iteration or optimization is needed: Leveraging the itertools module enables efficient infinite iteration, combination of multiple data sets, and generation of special permutations and combinations.

Conclusion

Python provides a rich set of features for performing iteration efficiently and concisely. By using a variety of techniques—from simple loops to advanced iteration over multiple sequences—you can greatly improve code readability and efficiency. Properly applying these methods makes Python programming even more flexible and powerful. Going forward, aim to master each feature as needed and continue writing efficient code.
年収訴求