Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- for i in '01234':
- print(i)
- the_iteratable = '01234'
- the_iterator = iter(the_iteratable)
- while True:
- try:
- i = next(the_iterator)
- except StopIteration:
- break
- print(i)
- '''
- # range(2, 10, 2)
- def my_range(start, stop, step):
- current = start
- while current < stop:
- yield current
- current += step
- '''
- gen_obj = iter(my_range(2, 10, 2))
- while True:
- try:
- print(next(gen_obj))
- except StopIteration:
- break
- '''
- '''
- for i in my_range(2, 10, 2):
- print(i)
- '''
- al@jfish python % python3
- Python 3.13.3 (main, Apr 8 2025, 13:54:08) [Clang 16.0.0 (clang-1600.0.26.6)] on darwin
- Type "help", "copyright", "credits" or "license" for more information.
- >>> for i in range(5):
- ... print(i)
- ...
- 0
- 1
- 2
- 3
- 4
- >>> range(5)
- range(0, 5)
- >>> type(range(5))
- <class 'range'>
- >>> r1 = range(5)
- >>> r2 = range(0, 10, 2)
- >>> next(r1)
- Traceback (most recent call last):
- File "<python-input-5>", line 1, in <module>
- next(r1)
- ~~~~^^^^
- TypeError: 'range' object is not an iterator
- >>> r1 = iter(r1)
- >>> r2 = iter(r2)
- >>>
- >>>
- >>>
- >>> next(r1)
- 0
- >>> next(r1)
- 1
- >>> next(r1)
- 2
- >>> next(r1)
- 3
- >>> next(r1)
- 4
- >>> next(r1)
- Traceback (most recent call last):
- File "<python-input-16>", line 1, in <module>
- next(r1)
- ~~~~^^^^
- StopIteration
- >>> range_obj = range(0, 10, 2)
- >>> iterator1 = iter(range_obj)
- >>> iterator2 = iter(range_obj)
- >>> next(iterator1)
- 0
- >>> next(iterator1)
- 2
- >>> next(iterator1)
- 4
- >>> next(iterator2)
- 0
- >>> next(iterator2)
- 2
- >>> next(iterator2)
- 4
- >>> # An iterable obj (like a range obj, string, list, dict.keys(), set obj) is passed to iter() whic\
- h returns an iterator obj.
- >>> i3 = iter(iterator1)
- >>> i3 == iterator1)
- File "<python-input-28>", line 1
- i3 == iterator1)
- ^
- SyntaxError: unmatched ')'
- >>> i3 == iterator1
- True
- >>> next(i3)
- 6
- >>> next(iterator2)
- 6
- >>> next(iterator2)
- 8
- >>> next(iterator2)
- Traceback (most recent call last):
- File "<python-input-33>", line 1, in <module>
- next(iterator2)
- ~~~~^^^^^^^^^^^
- StopIteration
- >>> next(iterator2)
- Traceback (most recent call last):
- File "<python-input-34>", line 1, in <module>
- next(iterator2)
- ~~~~^^^^^^^^^^^
- StopIteration
- >>> next(iterator2)
- Traceback (most recent call last):
- File "<python-input-35>", line 1, in <module>
- next(iterator2)
- ~~~~^^^^^^^^^^^
- StopIteration
- >>>
- >>>
- >>>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement