[Python] how the for loop works

Source: Internet
Author: User
If you understand it at the iteration level, you may have a deeper understanding of the working principle of. First, let's use dir to check what they have in common for the different types of range and str. If you understand it at the iteration level, you may have a deeper understanding of the working principle of.
First, let's use dir to check what they have in common for the different types of range and str.

>>> Dir (range) ['_ class _', '_ ins _', '_ delattr _', '_ dir __', '_ doc _', '_ eq _', '_ format _', '_ ge _', '_ getattribute __', '_ getitem _', '_ gt _', '_ hash _', '_ init _', '_ iter __', '_ le _', '_ len _', '_ lt _', '_ ne _', '_ new __', '_ reduce _', '_ performance_ex _', '_ repr _', '_ reversed _', '_ setattr __', '_ sizeof _', '_ str _', '_ subclasshook _', 'count', 'index', 'start', 'step ', 'STOP'] >>> dir (str) ['_ add _', '_ class _', '_ ins __', '_ delattr _', '_ dir _', '_ doc _', '_ eq _', '_ format __', '_ ge _', '_ getattribute _', '_ getitem _', '_ getnewargs _', '_ gt __', '_ hash _', '_ init _', '_ iter _', '_ le _', '_ len __', '_ lt _', '_ mod _', '_ mul _', '_ ne _', '_ new __', '_ reduce _', '_ performance_ex _', '_ repr _', '_ rmod _', '_ rmul __', '_ setattr _', '_ sizeof _', '_ str _', '_ subclasshook _', 'capitalize', 'casefold ', 'center', 'count', 'encoding', 'enableswith', 'pandtabs ', 'Find', 'format', 'format _ map', 'index ', 'isalnum', 'isalpha', 'isdecimal ', 'isdigit', 'isidentifier', 'islower', 'isnumeric ', 'isprintable', 'isspace', 'istitle ', 'isupper', 'join', 'ljust ', 'lower', 'lstrip', 'maketrans ', 'Partition', 'replace', 'rfind ', 'rindex ', 'Partition UST ', 'rpartition', 'rsplit', 'rdstrip', 'Split ', 'splits', 'startswith', 'strip', 'swapcase', 'title ', 'translate', 'uppper ', 'zfill'] view the two common attributes> set (dir (range) & set (dir (str )) {'_ hash _', '_ eq _', '_ ins _', '_ iter __', '_ getitem _', 'count', '_ lt _', '_ dir _', '_ le __', '_ subclasshook _', '_ ge _', '_ sizeof _', '_ format _', '_ len __', '_ ne _', '_ getattribute _', '_ delattr _', '_ performance_ex _', '_ gt __', '_ reduce _', '_ setattr _', '_ doc _', '_ class _', '_ new __', '_ repr _', '_ init _', 'index', '_ str __'}

We focus on the _ iter _ attribute. both of them have this function. if you look at other objects that can be iterated using the for loop, you can find this special method.
The object implementing this method is called iterable.
When we pass the object to the built-in iter () method in Python, an iterator is returned. the for loop uses this pattern to apply to all objects.
For example:

>>> Iter ([1, 2])
 
  
>>> Iter (range (0, 10 ))
  
   
>>> Iter ("abc ")
   
    
>>> The objects returned by the iter function are called iterator. you only need to call the next (iterator) method to return the next element.
   
  
 

Example:

>>> t = iter("abc")>>> next(t)'a'>>> next(t)'b'>>> next(t)'c'>>> next(t)Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   StopIteration
  
 

An exception is thrown when the iterator has no elements to iterate.
Here I will give the definition of itrable and iterator.
Iterable:
It can be passed to iter and an iteratot object is returned.
Iterator:
It can be passed to the next function and return the object of the next iteration element, and an exception is thrown at the end of the iteration.

Therefore, we will use the iterator to redefine your example.

>>> t = iter(range(90, 0, -1))>>> t
 
  >>> next(t)90>>> next(t)89>>> next(t)88
 

I hope you will have some gains.

For more articles about how the [Python] for loop works, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.