Python#s zip Function: Combining Iterables into Tuples

  • Share this:

Code introduction


Combine multiple iterables into a single iterable of tuples, returning an iterator of tuples, where each tuple contains the element from each of the argument iterables.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip(*iterables):
    """Zip multiple iterables together into a single iterable of tuples.

    Args:
        *iterables: An arbitrary number of iterables.

    Returns:
        An iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.

    Example:
        >>> list(zip([1, 2], ['a', 'b'], [True, False]))
        [(1, 'a', True), (2, 'b', False)]

    """
    # Create an iterator for each input iterable
    iterators = [iter(iterable) for iterable in iterables]
    
    # Define a helper function to get the next item from each iterator
    def get_next():
        for iterator in iterators:
            try:
                yield next(iterator)
            except StopIteration:
                # If any iterator is exhausted, raise StopIteration
                raise

    # Create an iterator that will return the next tuple from the iterators
    return zip(*get_next())