Python Zip and Unzip
Zip
zip()
is a built-in function that is used to combine two or more iterable objects into one, creating an iterator that produces tuples containing elements from each of the input iterables. The basic syntax of the zip()
function is as follows:
1syntax 2zip(iter1, iter2, ...)
Here is an example of using the zip()
function to combine two lists into one list and dict:
1colors = ["red", "green", "blue"] 2codes = ["#ff0000", "#00ff00", "#0000ff"] 3color_codes_list = list(zip(colors, codes)) 4color_codes_dict = dict(zip(colors, codes)) 5print(color_codes_list) 6print(color_codes_dict) 7 8Output: 9[('red', '#ff0000'), ('green', '#00ff00'), ('blue', '#0000ff')] 10{'red': '#ff0000', 'green': '#00ff00', 'blue': '#0000ff'}
zip()
function takes two lists colors
and codes
and returns an iterator that produces tuples containing one element from each list. These tuples can be converted to dictionary using dict() and list()
function.
zip with different length
In case the lists have different length, the zip()
function will stop when the shortest list is exhausted.
1colors = ["red", "green", "blue"] 2codes = ["#ff0000", "#00ff00"] 3color_codes_list = list(zip(colors, codes)) 4color_codes_dict = dict(zip(colors, codes)) 5print(color_codes_list) 6print(color_codes_dict) 7 8Output: 9[('red', '#ff0000'), ('green', '#00ff00')] 10{'red': '#ff0000', 'green': '#00ff00'}
Unzip
zip function can be used to unzip a list of tuples
1color_codes = [('red', '#ff0000'), ('green', '#00ff00')] 2colors, codes = list(zip(*color_codes)) 3print(colors) 4print(codes) 5 6Output: 7('red', 'green') 8('#ff0000', '#00ff00')
zip() function in Python is a powerful tool that allows you to combine multiple iterable objects into one. It can be used to create a new iterator that produces tuples containing elements from each of the input iterables. zip() can also be used to un