I. What Are Iterables and Iterators
Python provides a unified iteration mechanism, allowing different types of data to be traversed in the same way.
For example, strings, lists, tuples, sets, dictionaries, file objects, and generators can all participate in iteration.
# String
text = "Python"
# List
numbers = [10, 20, 30]
# Tuple
points = (1, 2, 3)
# Set
tags = {"Python", "Java", "Go"}
# Dictionary
user = {"name": "Alice", "age": 25}
for item in numbers:
print(item)
Although these objects have different internal structures, Python can traverse them using a unified for loop.
This unified capability comes from two core concepts:
- Iterable: An object that can provide an iterator.
- Iterator: An object that can produce elements one by one and keep track of the current traversal position.
The two are closely related, but they are not the same concept.
1. Iterable Objects
An iterable object is an object that can provide an iterator.
According to the Python iteration protocol, an object is considered iterable if it satisfies either of the following conditions:
- It implements the
__iter__()method, which returns an iterator. - For objects compatible with the legacy sequence protocol, it implements
__getitem__()starting from index0and raisesIndexErrorwhen the index is out of range.
Common iterable objects:
| Object | Iterable? | What Is Iterated |
|---|---|---|
str |
Yes | Characters |
list |
Yes | List elements |
tuple |
Yes | Tuple elements |
set |
Yes | Set elements |
dict |
Yes | Dictionary keys |
range |
Yes | Integer sequence |
bytes |
Yes | Byte values as integers |
| File object | Yes | File lines |
| Generator | Yes | Generated elements |
Example:
# String
for char in "Python":
print(char)
# List
for number in [10, 20, 30]:
print(number)
# By default, a dictionary iterates over its keys
user = {"name": "Alice", "age": 25}
for key in user:
print(key)
An important characteristic of an iterable object is that it can provide an iterator for traversal operations.
2. Iterator
An iterator is a special object responsible for providing data one by one in order.
An iterator must implement both of the following methods:
__iter__(): Returns the iterator itself.__next__(): Returns the next element; raisesStopIterationwhen there are no more elements.
Example:
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator)) # 10
print(next(iterator)) # 20
print(next(iterator)) # 30
Continuing to fetch elements:
print(next(iterator))
It raises:
StopIteration
Because all elements in the list have already been iterated over.
An iterator is not only responsible for providing elements but also needs to maintain the current traversal state.
3. Relationship Between the Two
They can be understood as follows:
- An iterable object is responsible for providing an iterator.
- An iterator is responsible for producing elements one by one.
- An iterator records traversal progress through its internal state.
- When the elements are exhausted,
StopIterationindicates the end of traversal.
flowchart TD
A["Iterable object"] --> B["Call iter()"]
B --> C["Get iterator"]
C --> D["Call next()"]
D --> E{"Are there more elements?"}
E -->|Yes| F["Return the next element"]
F --> D
E -->|No| G["Raise StopIteration"]
G --> H["Iteration ends"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
II. Checking and Using Iterable Objects
In real-world development, it is often necessary to determine whether an object supports iteration.
Python provides several ways to make this determination.
1. Using iter() to Check
The most direct way to check is to try calling iter().
data = [1, 2, 3]
iterator = iter(data)
print(iterator)
If the object is not iterable, calling iter() raises TypeError.
number = 100
iterator = iter(number)
# TypeError: 'int' object is not iterable
You can check this through exception handling:
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
print(is_iterable([1, 2, 3])) # True
print(is_iterable("Python")) # True
print(is_iterable(100)) # False
This approach directly verifies whether an object can be accepted by Python's iteration mechanism.
2. Using isinstance() to Check
Python's collections.abc module provides the Iterable abstract base class.
from collections.abc import Iterable
print(isinstance([1, 2, 3], Iterable)) # True
print(isinstance("Python", Iterable)) # True
print(isinstance(100, Iterable)) # False
You can also check custom objects:
from collections.abc import Iterable
class MyCollection:
def __init__(self, data):
self.data = data
def __iter__(self):
return iter(self.data)
obj = MyCollection([1, 2, 3])
print(isinstance(obj, Iterable)) # True
Note: instance checks against Iterable primarily rely on the abstract interface and its registration mechanism. For special legacy sequence-protocol objects, iter() may succeed, but isinstance(obj, Iterable) does not necessarily return True.
Therefore, if the goal is to confirm whether an object can actually participate in iteration, calling iter() directly is usually more reliable.
3. Iterable Objects Are Not Necessarily Iterators
This is one of the most easily confused points in Python's iteration mechanism.
A list is an iterable object, but the list itself is not an iterator.
numbers = [10, 20, 30]
print(iter(numbers) is numbers)
# False
A list needs to be passed to iter() to create a list iterator.
iterator = iter(numbers)
print(iterator is numbers)
# False
An iterator, however, when passed to iter(), usually returns itself:
iterator = iter(numbers)
print(iter(iterator) is iterator)
# True
This is an important feature of the iterator protocol.
4. The Same Iterable Can Create Multiple Iterators
For objects that can be iterated multiple times, such as lists and tuples, each call to iter() usually creates an independent iterator.
numbers = [10, 20, 30]
iterator1 = iter(numbers)
iterator2 = iter(numbers)
print(next(iterator1)) # 10
print(next(iterator1)) # 20
print(next(iterator2)) # 10
The two iterators have their own independent iteration states.
numbers = [10, 20, 30]
iterator1 = iter(numbers)
iterator2 = iter(numbers)
print(next(iterator1)) # 10
print(next(iterator2)) # 10
print(next(iterator1)) # 20
print(next(iterator2)) # 20
This shows that the list itself stores the data, while each iterator maintains its own iteration progress.
III. Python Iteration Protocol
The iteration protocol is the foundation of Python's unified traversal mechanism.
Understanding the iteration protocol explains why different types of objects can all use for loops.
1. The iter() Method
__iter__() is used to obtain an iterator.
For an iterable, calling this method should return an iterator.
numbers = [10, 20, 30]
iterator = numbers.__iter__()
print(type(iterator))
Equivalent to:
iterator = iter(numbers)
In actual development, prefer the built-in function iter() rather than calling the special method directly.
2. The next() Method
__next__() is used to obtain the next element.
numbers = [10, 20, 30]
iterator = iter(numbers)
print(iterator.__next__()) # 10
print(iterator.__next__()) # 20
print(iterator.__next__()) # 30
Equivalent to:
print(next(iterator))
When the iterator has no more elements, it must raise StopIteration.
3. Complete Requirements of the Iterator Protocol
An object that conforms to the iterator protocol must satisfy the following:
| Method | Purpose | Return Value |
|---|---|---|
__iter__() |
Returns the iterator itself | self |
__next__() |
Returns the next element | An element, or raises StopIteration |
This can be represented using the following structure:
class Iterator:
def __iter__(self):
return self
def __next__(self):
# Return the next element
# Raise StopIteration when there are no elements
pass
Note that pass is only a placeholder. A real iterator must implement state management and an end condition.
4. Protocol Differences Between Iterables and Iterators
| Comparison Dimension | Iterable | Iterator |
|---|---|---|
| Core responsibility | Provides an iterator | Produces elements one by one |
__iter__() |
Must conform to the iteration mechanism | Must be implemented and return itself |
__next__() |
Not necessarily implemented | Must be implemented |
| Stores iteration state | Not necessarily | Yes |
Can next() be called directly |
Not necessarily | Yes |
| Can it be used in a for loop | Yes | Yes |
| Can only be iterated once | Not necessarily | Usually cannot restart after exhaustion |
5. Using collections.abc to Check for Iterators
Python provides the Iterator abstract base class.
An iterator is also an iterable, because it must implement __iter__().
But an iterable is not necessarily an iterator.
IV. The Underlying Iteration Mechanism of the for Loop
The for loop is the most common way to traverse data in Python.
It is not syntax designed specifically for lists; rather, it is built on a unified iteration protocol.
1. Basic Usage of the for Loop
```python numbers = [10, 20, 30] for number in numbers: print(number) ```Output:
```text 10 20 30 ```Whether you are iterating over a list, tuple, set, dictionary, file, or generator, the basic syntax is the same.
2. How the for Loop Executes
Conceptually, a for loop performs the following operations:
- Obtain the iterator of the iterable.
- Call the iterator to get the next element.
- Bind the element to the loop variable.
- Execute the loop body.
- Continue getting the next element.
- End the loop upon encountering
StopIteration.
Corresponding flow:
```mermaid flowchart TD A["Start for loop"] --> B["Get iterator via iter()"] B --> C["Call next()"] C --> D{"Element obtained?"} D -->|Yes| E["Bind loop variable"] E --> F["Execute loop body"] F --> C D -->|No| G["Catch StopIteration"] G --> H["Exit loop"] style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155 style D fill:#FFF5DE,stroke:#E8D29A,color:#334155 style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155 style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155 ```3. Manually Simulating a for Loop
You can use iter() and next() to simulate a for loop.
Output:
```text 10 20 30 ```This code demonstrates the basic mechanism behind the for loop.
But in everyday development, you usually do not need to catch StopIteration manually; using for directly is more concise.
4. Differences Between the for Loop and next()
| Comparison | for loop | next() |
|---|---|---|
| Automatically obtains an iterator | Yes | No |
| Automatically handles the termination signal | Yes | Raises StopIteration by default |
| Retrieves elements one by one | Yes | Yes |
| Suitable for everyday iteration | Very suitable | Suitable for fine-grained control |
| Requires manual state management | Usually not | Usually yes |
next() also supports a default value:
If the iterator is already exhausted, next(iterator, default) returns the specified default value instead of raising StopIteration.
Note: If the iterator itself produces None as an element, you cannot tell from the return value alone whether it is an actual element or the default value.
V. Iterator State and One-Time Consumption
One of the biggest differences between an iterator and a list is that an iterator keeps track of its traversal state.
1. Iterators Have State
numbers = [10, 20, 30, 40]
iterator = iter(numbers)
print(next(iterator)) # 10
print(next(iterator)) # 20
At this point, the iterator has already consumed the first two elements.
Continue calling it:
print(next(iterator)) # 30
print(next(iterator)) # 40
The iterator does not automatically go back to the beginning.
2. An Iterator Cannot Be Reset Automatically After It Is Exhausted
numbers = [10, 20, 30]
iterator = iter(numbers)
for number in iterator:
print(number)
for number in iterator:
print(number)
The second loop produces no output because the first loop has already consumed the iterator.
If you need to traverse it again, you should obtain a new iterator:
numbers = [10, 20, 30]
iterator = iter(numbers)
for number in iterator:
print(number)
iterator = iter(numbers)
for number in iterator:
print(number)
Here, calling iter(numbers) again creates a new list iterator.
3. Iterables Can Usually Be Traversed Repeatedly
Iterables such as lists, tuples, and strings can usually have iter() called on them multiple times to create new iterators.
numbers = [10, 20, 30]
for number in numbers:
print(number)
for number in numbers:
print(number)
Both loops will output the complete contents.
However, not all iterables can be traversed repeatedly.
For example, a generator object is itself an iterator, and it usually does not recover automatically after being consumed.
4. Iterables Are Not Necessarily Reusable
A file object is a typical example:
with open("data.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
# The file iterator has reached the end of the file
for line in file:
print(line.strip())
The second loop has no content because the file object's read position has already reached the end.
If you need to read it again, you can use seek(0), provided that the file object supports seeking:
with open("data.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
file.seek(0)
for line in file:
print(line.strip())
Therefore, you need to distinguish between:
- Iterable: can provide an iterator.
- Repeatably traversable: can start a new traversal process from the beginning.
- Iterator: usually a stateful object that is consumed once.
VI. Common Built-in Iterables in Python
Many built-in types in Python support iteration.
1. Strings (str)
Iterating over a string returns its characters one by one.
text = "Python"
for char in text:
print(char)
Strings are immutable sequences, so ordinary string operations will not change the original string during iteration.
2. Lists (list)
Iterating over a list returns its elements in order.
numbers = [10, 20, 30]
for number in numbers:
print(number)
A list iterator usually accesses elements in the list according to the current index.
Note: Modifying a list's structure while iterating over it may cause elements to be skipped, visited repeatedly, or produce other unexpected results.
For example:
numbers = [1, 2, 3, 4]
for number in numbers:
if number == 2:
numbers.remove(number)
print(numbers)
After an element is deleted, the positions of subsequent elements change, which may cause some elements to be skipped.
A safer approach is to iterate over a copy:
numbers = [1, 2, 3, 4]
for number in numbers.copy():
if number == 2:
numbers.remove(number)
print(numbers)
Or use a list comprehension:
numbers = [1, 2, 3, 4]
numbers = [number for number in numbers if number != 2]
3. Tuple
Iterating over a tuple is similar to a list, but the tuple itself is immutable.
user = ("Alice", 25, "Beijing")
for item in user:
print(item)
Tuples are suitable for storing data with a fixed structure.
4. Set
Sets support iteration, but do not guarantee element order.
numbers = {10, 20, 30}
for number in numbers:
print(number)
If you need a definite sorted order, you can use:
for number in sorted(numbers):
print(number)
5. Dictionary
A dictionary iterates over its keys by default.
user = {
"name": "Alice",
"age": 25,
"city": "Beijing"
}
for key in user:
print(key)
To iterate over key-value pairs:
for key, value in user.items():
print(key, value)
Dictionaries provide three commonly used views:
| Method | Returns |
|---|---|
keys() |
Keys view |
values() |
Values view |
items() |
Key-value pairs view |
These views are all iterable objects and can be used directly in a for loop.
6. range object
range is an iterable object that represents a sequence of integers.
numbers = range(1, 6)
for number in numbers:
print(number)
Output:
1
2
3
4
5
range does not need to create a list containing all the integers in advance, so it is suitable for representing large integer ranges.
numbers = range(0, 1000000)
print(len(numbers))
range supports indexing, slicing, and membership testing, but it is not itself an iterator.
numbers = range(5)
print(iter(numbers) is numbers) # False
7. File object
File objects can be iterated line by line.
with open("data.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
File iteration usually reads data on demand, so you do not need to load the entire file into memory at once.
For large text files, this approach usually saves more memory than reading all the content at once with read().
VII. Custom iterable objects
After understanding the built-in types, you can go further and implement your own iterable objects.
A custom iterable object usually provides an iterator by implementing __iter__().
1. The simplest custom iterable object
class NumberCollection:
def __init__(self, numbers):
self.numbers = numbers
def __iter__(self):
return iter(self.numbers)
numbers = NumberCollection([10, 20, 30])
for number in numbers:
print(number)
Here, NumberCollection does not implement __next__(), but it can still be iterated over.
The reason is that its __iter__() returns a list iterator.
2. Using a generator to implement iter()
You can also use yield inside the __iter__() method.
class NumberCollection:
def __init__(self, numbers):
self.numbers = numbers
def __iter__(self):
for number in self.numbers:
yield number
numbers = NumberCollection([10, 20, 30])
for number in numbers:
print(number)
Here, __iter__() is a generator function.
When it is called, it does not execute the entire loop immediately; instead, it returns a generator object.
3. Custom iterable with filtering conditions
class EvenNumbers:
def __init__(self, numbers):
self.numbers = numbers
def __iter__(self):
for number in self.numbers:
if number % 2 == 0:
yield number
numbers = EvenNumbers([1, 2, 3, 4, 5, 6])
for number in numbers:
print(number)
Output:
2
4
6
This design encapsulates data processing rules in the iterable object, allowing the caller to care only about the traversal result.
4. Advantages of custom iterables
- Encapsulates the data source.
- Encapsulates traversal rules.
- Supports creating iterators multiple times.
- Supports
forloops. - Can produce data on demand.
- Easy to combine and extend.
Note: if __iter__() returns a brand-new generator each time, it can usually be traversed again; if it returns a shared iterator that has already been consumed, it may not be possible to traverse it repeatedly.
VIII. Custom Iterators
In addition to custom iterables, you can also directly implement the iterator protocol.
This approach is suitable for scenarios that require precise control over traversal state.
1. Implement a number iterator
class CountIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
value = self.current
self.current += 1
return value
iterator = CountIterator(1, 5)
for number in iterator:
print(number)
Output:
1
2
3
4
5
This iterator contains three important parts:
current: the current traversal position.end: the traversal end position.__next__(): produces the next element and updates the state.
2. Manually calling next()
iterator = CountIterator(1, 3)
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
Calling it again:
next(iterator)
will trigger StopIteration.
3. Using the default value of next()
iterator = CountIterator(1, 2)
print(next(iterator, None)) # 1
print(next(iterator, None)) # 2
print(next(iterator, None)) # None
This allows the caller to avoid explicitly catching StopIteration.
4. Implement a repeatedly traversable container
If you want an object to be traversable multiple times, the container itself should not bear one-time iteration state.
You can make each call to __iter__() create a new iterator.
class NumberRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
current = self.start
while current <= self.end:
yield current
current += 1
numbers = NumberRange(1, 3)
print(list(numbers))
print(list(numbers))
The two outputs are the same:
[1, 2, 3]
[1, 2, 3]
Because each call to iter() returns a new generator.
5. Difference Between Custom Iterators and Custom Iterable Objects
| Design approach | Implementation | Characteristics |
|---|---|---|
| Custom iterable object | __iter__() |
Provides an iterator |
| Custom iterator | __iter__(), __next__() |
Manages iteration state itself |
| Generator-based iterable object | Uses yield in __iter__() |
Simplifies iterator implementation |
In engineering practice, if there is no special state-management requirement, it is usually preferable to use generators to implement iteration logic.
IX. Generators and Iterators
Generators are a very important iteration tool in Python.
They can generate data on demand, without needing to build a complete data collection in advance.
Generators are closely related to iterators:
A generator is a special implementation of an iterator.
1. What Is a Generator
A generator is an iterator that can pause and resume during execution.
Python provides two main ways to create them:
- Generator functions: functions that contain
yield. - Generator expressions: lazy expressions created using parentheses.
2. Generator Functions
A regular function uses return to return a result.
def get_numbers():
return [1, 2, 3]
result = get_numbers()
print(result)
A generator function uses yield to produce results one at a time:
def get_numbers():
yield 1
yield 2
yield 3
generator = get_numbers()
print(next(generator)) # 1
print(next(generator)) # 2
print(next(generator)) # 3
When next() is called again, the generator raises StopIteration.
3. How yield Works
yield and return have clear differences.
| Comparison aspect | return | yield |
|---|---|---|
| Primary purpose | Returns the function result | Produces an iteration value |
| Ends the function? | Yes | Pauses the function |
| Preserves local state? | Does not continue after the function ends | Yes |
| Supports continued execution? | No | Yes |
| Creates a generator? | No | Yes, when the function is defined |
Example:
def counter():
print("开始")
yield 1
print("继续")
yield 2
print("结束")
generator = counter()
print(next(generator))
print(next(generator))
Execution process:
开始
1
继续
2
The final 结束 has not yet been output, because the generator has not yet executed the code after the last yield.
Calling it again:
next(generator)
will execute the remaining code and then raise StopIteration.
4. Generator Expressions
A list comprehension immediately generates a list:
numbers = [x * 2 for x in range(5)]
print(numbers)
# [0, 2, 4, 6, 8]
A generator expression uses parentheses:
numbers = (x * 2 for x in range(5))
print(numbers)
# <generator object ...>
Iterate over it when you need to get elements:
for number in numbers:
print(number)
5. Difference Between List Comprehensions and Generator Expressions
| Comparison dimension | List comprehension | Generator expression |
|---|---|---|
| Syntax | [] |
() |
| Result type | list |
Generator |
| Whether all results are computed immediately | Yes | No |
| Whether indexing is supported | Yes | No |
| Whether it can be iterated repeatedly | Yes | No; a generator is usually consumed once |
| Memory characteristics | Stores all results | Produces results on demand |
| Use cases | Moderate data volume; repeated access is needed | Large data streams; lazy evaluation |
Example:
# List comprehension
numbers_list = [x * 2 for x in range(5)]
# Generator expression
numbers_generator = (x * 2 for x in range(5))
print(type(numbers_list))
print(type(numbers_generator))
6. State preservation in generators
When a generator pauses, it retains its execution state, including:
- Local variables.
- The current execution position.
- The state of loops that have not yet completed.
- Relevant information in the current execution context.
For example:
def counter():
number = 1
while number <= 3:
yield number
number += 1
generator = counter()
print(next(generator)) # 1
print(next(generator)) # 2
print(next(generator)) # 3
Each time execution resumes, it continues from the position where it was last paused.
7. Lazy evaluation in generators
Lazy evaluation means that data is calculated only when it is actually needed.
def generate_numbers():
for number in range(5):
print("生成数据:", number)
yield number
generator = generate_numbers()
print("生成器已创建")
print(next(generator))
print(next(generator))
Output:
生成器已创建
生成数据: 0
0
生成数据: 1
1
When the generator is created, the loop in the function is not executed immediately.
Execution starts only when next() is called.
8. Use cases for generators
- Reading large files line by line.
- Large-scale data processing.
- Processing database results in batches.
- Network data streams.
- Generating infinite sequences.
- Stream computing.
- Multi-stage data processing pipelines.
10. Iteration Tools and Built-in Functions
Python provides many built-in functions and standard library tools based on iteration mechanisms.
They can reduce manual traversal code and improve data processing efficiency.
1. enumerate()
enumerate() can obtain both the index and the value during iteration.
names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names):
print(index, name)
Output:
0 Alice
1 Bob
2 Charlie
You can also specify the starting index:
for index, name in enumerate(names, start=1):
print(index, name)
Output:
1 Alice
2 Bob
3 Charlie
enumerate() returns an iterator.
2. zip()
zip() can combine elements from multiple iterables by position.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 28]
for name, age in zip(names, ages):
print(name, age)
Output:
Alice 25
Bob 30
Charlie 28
By default, zip() stops when the shortest iterable is exhausted.
Python 3.10 and later support strict=True:
names = ["Alice", "Bob"]
ages = [25]
for name, age in zip(names, ages, strict=True):
print(name, age)
When the lengths don't match, a ValueError is raised.
3. map()
map() applies a function to each element in an iterable.
numbers = [1, 2, 3, 4]
result = map(lambda x: x * 2, numbers)
print(list(result))
# [2, 4, 6, 8]
map() returns an iterator-style result and does not generate the full list immediately.
4. filter()
filter() filters elements based on a condition.
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))
# [2, 4, 6]
filter() is also a lazy iteration tool.
5. reversed()
reversed() returns a reverse iterator.
numbers = [1, 2, 3, 4]
for number in reversed(numbers):
print(number)
Output:
4
3
2
1
Note: not all iterables support reversed(). Typically, the object is required to support the reverse iteration protocol, or to have both a length and integer index access.
6. sorted()
sorted() takes an iterable and returns a new sorted list.
numbers = [5, 2, 4, 1, 3]
result = sorted(numbers)
print(result)
# [1, 2, 3, 4, 5]
Unlike sort(), sorted() does not modify the original data in place.
7. all() and any()
Both all() and any() can work with iterables.