Files
30-seconds-of-code/snippets/zip.md
Angelos Chalaris cb8bbd9745 Update formatting
Update formatting in every_nth
Update formatting in shuffle
Update formatting in has_duplicates
Update formatting in group_by
Update formatting in sum_by
Update formatting in zip
Update formatting in longest_item
Update formatting in bifurcate_by
Update formatting in difference_by
Update formatting in clamp_number
Update formatting in min_by
Update formatting in max_by
Update formatting in union
Update formatting in n_times_string
Update formatting in check_prop
Update formatting in chunk
Update formatting in transpose
Update formatting in bifurcate
Update formatting in union_by
Update formatting in initialize_list_with_range
Update formatting in most_frequent
2020-01-03 13:06:54 +02:00

28 lines
850 B
Markdown

---
title: zip
tags: list,math,intermediate
---
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`).
```py
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
```
```py
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]]
```