- BASICS
- Statements
- Operators
- Functions
- Incremental
- Errors
- FUNCTIONS
- Recursion
- Objects
- Lambda
- STRINGS
- Immutable
- Raw Strings
- Validation
- Config
- Security
- CLASS
- Definition
- Attributes
- Functional
- Methods
- COLLECTIONS
- Lists
- Dictionaries
- Efficiency
- Tree
-
Iterator
- Tuples
- References
- STORAGE
- Files
- Databases
- Pipes
- With Open
- Shelve
- Zip
- Csv
- Json
Iterable
An iterable object returns an iterator when passed to the build-in function iter()
A = [1, 2, 3]
I = iter(A) # iterator
print(next(I)) # 1
print(next(I)) # 2
print(next(I)) # 3
try:
print(next(I))
except StopIteration:
print("StopIteration")
Loop
A loop implicitly creates an iterator from the iterable object and calls its next() method.
A = [1, 2, 3]
for i in A:
print(i) # 1, 2, 3
Any Object
An iterator can be used with any iterable object, not just lists.
s = "abc"
I = iter(s)
print(next(I))
print(next(I))
print(next(I))
try:
print(next(I))
except StopIteration:
pass
Last update: 531 days ago