Skip to main content

Command Palette

Search for a command to run...

Zip Function in Python

Published
1 min readView as Markdown
Zip Function in Python
A

I am a Tech enthusiast interested to learn new things from everyone and post my learning in public.

Creates a list of elements, grouped based on the position in the original lists.

Use max combined with a list comprehension to get the length of the longest list in the arguments. Loops for max_length times grouping elements. If lengths of lists vary fill_value is used. By default fill_value is None.

Note: this function can also be implemented via itertools.zip_longest()

def zip(*args, fillvalue=None):
    max_length = max([len(lst) for lst in args])
    result = []
    for i in range(max_length):
        result.append([
            args[k][i] if i < len(args[k]) else None for k in range(len(args))
        ])
    return result
#input and output:
zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]

More from this blog

D

DEVS-OnThe-PUB

18 posts

The Content here will surely impact you, even if its in a small way. A place where Things are without bias...