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:
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-inlist、tupleThey 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:
After running, you will see:
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:
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)
2. Only traverse values:.values()
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:
here
key, 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:
You'll see the output letter by letter:P、y、t、h、o、n。
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:
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:
Output:
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):
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:
⚠️ 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:
2. Iterate after sortingsorted()
sorted()A new ordered sequence will be generated, and the original data will not be modified:
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)。
You can deliberately change the return value to the wrong one to see if the test works.
Summarize
- Python via
for...inSyntax implements iteration, safe and intuitive list、tuple、dict、strThey 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 timezip()Multiple independent sequences can be bundled and iterated togetherreversed()andsorted()Can easily change the traversal ordercollections.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!

