Dino Geek, try to help you

How does the iteration protocol work in Python?


Iteration in Python is based upon the iteration protocol which consists of two objects: the iterable and the iterator.

1. Iterable: An iterable is an object (usually a data structure like lists, tuples, sets, dictionaries, etc.) that can be represented as a sequence. It implements the **iter**() method which returns an iterator object or the **getitem**() method for indexed lookup.

1. Iterator: An iterator is an object tied to the iterable which allows traversing through all the elements within the iterable one at a time. It implements the **next**() method which returns the next value from the iterator. If there are no more items to be returned, it raises a StopIteration exception.

Here is how the process works:

a. The iter() built-in function is called on an iterable object which makes it an iterator.

b. The next() built-in function is called on the iterator object to fetch and return the next value. If there is no value left, a StopIteration exception is raised.

c. This process of calling next() repeatedly (often done implicitly within a for loop or list comprehension until a StopIteration exception is encountered and the loop is exited) is what makes up iteration in Python.

Example:

my\_list = [1, 2, 3, 4] my_iter = iter(my_list) print(next(my\_iter)) # Prints 1 print(next(my\_iter)) # Prints 2 #… this can be continued until the iteration ends

or,

for i in my\_list: print(i) #… this automatically continues until the iteration ends without explicitly calling next() or worrying about StopIteration.

Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use