title: Iterate description:Python iteration (Iteration) tutorial

Python iteration (Iteration) tutorial

Hello everyone!今天我们来聊一聊 Python 里最常用、最基础的概念之一 —— 迭代。 Once you master it, you can use the shortest code to easily traverse various data such as lists, dictionaries, and strings. Writing programs is not only smooth, but also very "Pythonic".


What is iteration?

Iteration, simply put, is the process of taking elements out of a "string of things" one at a time. Many languages ​​require manual maintenance of indexes, writingwhileLoop to access elements one by one, and Python gives us a very elegant syntax:

for 变量 in 可迭代对象:
    处理变量

this isfor...incycle. With it, you don't need to worry about indexing or crossing boundaries, just focus on "what do I want to do with each element".


Basic iteration: start with the most common sequence

Python built-inlisttupleThey are all "iterable objects" and can be put directly intofor...inIt can be used within.

1. List

Let's say you have a list of fruits:

fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(f"I love {fruit}!")

After running, you will see:

I love apple!
I love banana!
I love orange!

No need to write at allfruits[0]fruits[1]Such a subscript.

2. Tuple

The same goes for tuples, which can be accessed one by one in the same way:

colors = ('red', 'green', 'blue')
for color in colors:
    print(color)

Special iteration: three "opening methods" of dictionary

Dictionaries are also iterable objects, but only their keys are traversed by default. Python is also prepared for everyone.values()and.items()Two methods allow you to flexibly traverse values ​​or key-value pairs.

1. Only traverse keys (default behavior)

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key in person:
    print(f"Key: {key}")

2. Only traverse values:.values()

for value in person.values():
    print(f"Value: {value}")

3. Traverse keys and values ​​together:.items()+ tuple unpacking

This is the most commonly used dictionary iteration method, getting the keys and values ​​at once:

for key, value in person.items():
    print(f"{key}: {value}")

herekey, valueIn fact, it uses tuple unpacking which will be introduced later, which is very convenient.


Hidden skill: Strings can also be iterated

A string is essentially a "sequence of characters", so put it directly intofor...inHere you can extract each character one by one:

text = "Python"
for char in text:
    print(char)

You'll see the output letter by letter:Python


Advanced 1: Determine whether an object can be iterated

"Single values" such as integers and floating point numbers cannot be iterated over - if you tryfor i in 123, the program will report an error. If you are not sure whether an object is iterable, you can usecollections.abcin moduleIterableDo the test:

from collections.abc import Iterable

print(isinstance('abc', Iterable))  # True  字符串可迭代
print(isinstance([1,2,3], Iterable))# True  列表可迭代
print(isinstance(123, Iterable))    # False 整数不可迭代

This technique is especially useful when writing functions and checking parameters.


Advanced 2: Iterate with index ——enumerate()

Sometimes you need both the element itself and its position (such as updating a value in the original list). enumerate()will help you generate(索引, 元素)Pairing:

fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

Output:

Index 0: apple
Index 1: banana
Index 2: orange

Advanced 3: Iterate multiple sequences simultaneously

Python supports two elegant ways to iterate over multiple sequences simultaneously.

1. Tuple unpacking - when the sequence itself is a tuple

A lot of data naturally exists in the form of pairs, such as coordinates(x, y)

coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
    print(f"x: {x}, y: {y}")

Each time through the loop,xandyBind to the two values ​​​​in the tuple respectively. This is called tuple unpacking.

2. zip()—— "Package" multiple independent sequences together

If the data is spread across several different lists, you can usezip()Merge them into a set of tuples like "zippers", and then unpack them:

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

⚠️ Note: If the length of each sequence is inconsistent,zip()The shortest one will prevail, and the excess will be silently ignored.


Advanced 4: Reverse iteration and post-sort iteration

Python has two built-in functions to help you easily change the order of traversal.

1. Reverse iterationreversed()

Traverse the sequence backwards:

numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
    print(num)

2. Iterate after sortingsorted()

sorted()A new ordered sequence will be generated, and the original data will not be modified:

numbers = [3, 1, 4, 1, 5, 9, 2]
for num in sorted(numbers):
    print(num)

Practical exercise: Find the minimum and maximum values ​​in a list

After learning how to iterate, you can try to write a function that inputs a list of numbers and returns its minimum and maximum values. If the list is empty, return(None, None)

def findMinAndMax(L):
    if not L:  # 空列表情况
        return (None, None)

    min_val = max_val = L[0]
    for num in L:
        if num < min_val:
            min_val = num
        if num > max_val:
            max_val = num
    return (min_val, max_val)

# 简单的单元测试
if findMinAndMax([]) != (None, None):
    print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
    print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('测试失败!')
else:
    print('🎉 测试成功!')

You can deliberately change the return value to the wrong one to see if the test works.


Summarize

  • Python via for...in Syntax implements iteration, safe and intuitive
  • listtupledictstrThey are all iterable objects and can be put directly into the loop.
  • Dictionary default iteration key, available.values().items()Iterate over values ​​and key-value pairs separately
  • enumerate()Can get index and element at the same time
  • zip()Multiple independent sequences can be bundled and iterated together
  • reversed()andsorted()Can easily change the traversal order
  • collections.abc.IterableCan determine whether an object is iterable

Mastering these iteration techniques, the code you write will be more concise, flexible, and closer to the essence of Python. I hope this tutorial can help you lay a solid foundation and continue learning Python happily!