- Hands-On Penetration Testing with Python
- Furqan Khan
- 319字
- 2021-07-02 14:13:54
Iteration, iterable, and iterator
Iteration: An iteration is a process wherein a set of instructions or structures are repeated in a sequence a specified number of times or until a condition is met. Each time the body of a loop executes, it's said to complete one iteration.
Iterable: An iterable is an object that has an __iter__ method, which returns an iterator. An iterator is any object that contains a sequence of elements that can be iterated over, and then an operation can be performed. Python strings, lists, tuples, dictionaries, and sets are all iterables as they implement the __iter__ method. Take a look at the following snippet to see an example:

In the preceding code snippet, we declare a string a and place the value hello value in it. To see all the built-in methods of any object in Python, we can use the dir(<object>) method. For strings, this returns us all the operations and methods that can be carried out on the string type. In the second row, the 5th operation is the iter method we mentioned previously. It can be seen that iter(a) returns a string iterator:

Likewise, a list object's iter method would return a list iterator, as previously shown.
Iterator: An iterator is an object with a __next__ method. The next method always returns the next element of the sequence over which the original iter() method is called, starting from index 0. This is shown in the following code snippet:

As can be seen in the examples for both string and list, the next method over the iterator will always return us the next element in the sequence or the object that we are iterating over. It must be noted that the iterator only moves forwards, and if we want iter_a or list_itr to go back to any element, we must reinitialize the iterator to the original object or sequence:

- TypeScript入門與實(shí)戰(zhàn)
- DevOps入門與實(shí)踐
- HTML5游戲開發(fā)案例教程
- 零基礎(chǔ)學(xué)MQL:基于EA的自動(dòng)化交易編程
- Building RESTful Python Web Services
- 速學(xué)Python:程序設(shè)計(jì)從入門到進(jìn)階
- LabVIEW虛擬儀器程序設(shè)計(jì)從入門到精通(第二版)
- Django 3.0應(yīng)用開發(fā)詳解
- QlikView Unlocked
- MongoDB Cookbook(Second Edition)
- WildFly Cookbook
- 你真的會(huì)寫代碼嗎
- Modular Programming with JavaScript
- C++服務(wù)器開發(fā)精髓
- JSP應(yīng)用與開發(fā)技術(shù)(第3版)