- 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:

- Implementing VMware Horizon 7(Second Edition)
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- 軟件安全技術(shù)
- C程序設(shè)計(jì)簡明教程(第二版)
- 移動(dòng)UI設(shè)計(jì)(微課版)
- Practical UX Design
- 實(shí)戰(zhàn)Java程序設(shè)計(jì)
- Django:Web Development with Python
- Rust Cookbook
- STM32F0實(shí)戰(zhàn):基于HAL庫開發(fā)
- 用Python實(shí)現(xiàn)深度學(xué)習(xí)框架
- 算法訓(xùn)練營:提高篇(全彩版)
- Python大學(xué)實(shí)用教程
- Java Web從入門到精通(第3版)
- 深入實(shí)踐Kotlin元編程