Python Zip Function: Combining Iterables into Tuples

  • Share this:

Code introduction


The function takes any number of iterable objects as arguments and returns an iterator that will yield tuples composed of elements from the corresponding positions of these iterables. If any of the iterables have been exhausted, the corresponding element in the tuple will be replaced with None.


Technology Stack : Built-in function

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip(*iterables):
    """将多个可迭代对象组合成一个个元组的迭代器"""
    iters = [iter(it) for it in iterables]
    while True:
        yield tuple(next(it, None) for it in iters)