Sobes.tech
Junior

Provide examples of using the zip function in Python.

sobes.tech AI

Answer from AI

The zip() function combines elements from multiple iterable objects into tuples. Iteration stops when the shortest iterable is exhausted.

Examples:

  • Combining two lists:

    # Combining indices and values
    indices = [0, 1, 2]
    values = ['a', 'b', 'c']
    zipped_list = list(zip(indices, values))
    # zipped_list will be [(0, 'a'), (1, 'b'), (2, 'c')]
    
  • Combining three iterable objects:

    # Combining lists and a string
    numbers = [1, 2, 3]
    letters = ['x', 'y', 'z']
    symbols = "!@#"
    zipped_multiple = list(zip(numbers, letters, symbols))
    # zipped_multiple will be [(1, 'x', '!'), (2, 'y', '@'), (3, 'z', '#')]
    
  • Using zip() with loops:

    # Iterating over zipped_list
    names = ['Alice', 'Bob', 'Charlie']
    ages = [30, 25, 35]
    for name, age in zip(names, ages):
        print(f"{name} is {age} years old.")
    
  • Unpacking a zipped object with *:

    # Zipped list
    zipped_data = [(0, 'a'), (1, 'b'), (2, 'c')]
    # Unpacking into two separate lists
    indices, values = zip(*zipped_data)
    # indices will be (0, 1, 2) (tuple)
    # values will be ('a', 'b', 'c') (tuple)
    
  • Creating a dictionary using zip:

    # Creating a dictionary from two lists
    keys = ['apple', 'banana', 'orange']
    values = [10, 20, 15]
    fruit_prices = dict(zip(keys, values))
    # fruit_prices will be {'apple': 10, 'banana': 20, 'orange': 15}
    
  • Working with iterable objects of different lengths:

    # Zip stops at the shortest iterable
    short_list = [1, 2]
    long_list = ['a', 'b', 'c', 'd']
    zipped_unequal = list(zip(short_list, long_list))
    # zipped_unequal will be [(1, 'a'), (2, 'b')]