9 1-Iterators
9 1-Iterators
ipynb - Colab
keyboard_arrow_down Iterators
Iterators are advanced Python concepts that allow for efficient looping and memory management. Iterators provide a way to access elements
of a collection sequentially without exposing the underlying structure.
my_list=[1,2,3,4,5,6]
for i in my_list:
print(i)
1
2
3
4
5
6
type(my_list)
list
print(my_list)
[1, 2, 3, 4, 5, 6]
## Iterator
iterator=iter(my_list)
print(type(iterator))
<class 'list_iterator'>
iterator
<list_iterator at 0x27a325efb20>
next(iterator)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Cell In[17], line 3
1 ## Iterate through all the element
----> 3 next(iterator)
StopIteration:
iterator=iter(my_list)
try:
print(next(iterator))
except StopIteration:
print("There are no elements in the iterator")
# String iterator
my_string = "Hello"
string_iterator = iter(my_string)
print(next(string_iterator)) # Output: H
print(next(string_iterator)) # Output: e
H
e
https://colab.research.google.com/drive/1tTGpuUN6Loawxm3H3iujxs6bkL24Hduh#printMode=true 1/2
7/18/24, 10:44 AM 9.1-Iterators.ipynb - Colab
https://colab.research.google.com/drive/1tTGpuUN6Loawxm3H3iujxs6bkL24Hduh#printMode=true 2/2