Python uses the zip function to traverse multiple iterator examples at the same time _python

Source: Internet
Author: User
Tags zip in python

Objective

This article is mainly about how Python uses the zip function to traverse multiple iterators at the same time, and the version in the text is the Python3,zip function, which is a built-in Python function. The following words do not say more, to see the detailed content.

Application examples

>>> List1 = [' A ', ' B ', ' C ', ' d ']
>>> list2 = [' Apple ', ' boy ', ' cat ', ' dog ']
>>> for X, Y in-Zip (List1, list2):
  print (x, ' is ', y)
# output ' A is ' Apple B-is boy C-is
cat D is
dog

This makes it very simple to iterate through two lists at the same time, very pythonic!!!

Principle explanation

The zip function in Python3 can encapsulate two or more than two iterators into generators, which get the next value of the iterator from each iterator, and then assemble the values into tuples (tuple). Thus, the zip function implements a parallel traversal of multiple iterators.

Attention

If the input iterator length is different, then, as long as there is an iterator to traverse, the zip will no longer produce tuples, the zip would terminate prematurely, which may lead to unexpected results, should be observed. If you are unsure whether the list encapsulated by the zip is equal, you can instead use the Zip_longest function in the Itertools built-in module, which does not care whether their length is equal or not.

In the Python2, a zip is not a generator, it traverses these iterators in parallel, assembles the tuples, and returns the list of these tuples once and for all, which can consume a lot of memory and cause the program to crash, and if you want to traverse a large number of iterators in Python2, recommend using Itertools the Izip function in the built-in module.

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

Related Article

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.