30 seconds of python

  Back to Home

zip

listmathintermediate

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

Use max combined with list comprehension to get the length of the longest list in the arguments. Loop for max_length times grouping elements. If lengths of lists vary, use fill_value (defaults to None).

def zip(*args, fill_value=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 fillvalue for k in range(len(args))
    ])
  return result