How to Use “zip()” in Python and combine it with “enumerate()”

On processing symmetric lists/same-sized series

Pavol Kutaj
2 min readMar 28, 2022

The aim of this page📝is to cover the zip operator and combine it with enumerate to achieve elegant processing and modification of two same-size (symmetrical) lists / iterable series.

  • it synchronizes the iteration over two symmetrical iterable series
  • in other words, it simplifies the work on two lists of the same size
  • both of the items are placed as a pair inside a tuple
Sunday = [12, 14, 15, 15, 17, 21, 22, 23, 22, 20, 18]
Monday = [12, 14, 18, 22, 19, 33, 17, 15, 14, 18, 18]

for hourlyTemp in zip(Sunday, Monday):
print(hourlyTemp)

# >>> (12, 12)
# >>> (14, 14)
# >>> (15, 18)
# >>> (15, 22)
# >>> (17, 19)
# >>> (21, 33)
# >>> (22, 17)
# >>> (23, 15)
# >>> (22, 14)
# >>> (20, 18)
# >>> (18, 18)
  • this in turn means you can use tuple unpacking to work with both values within a single loop
for sun, mon in zip(Sunday, Monday):
print("average =", (sun + mon)/2)

# >>> average = 12.0
# >>> average = 14.0
# >>> average = 16.5
# >>> average = 18.5
# >>> average = 18.0
# >>> average = 27.0
# >>> average = 19.5
# >>> average = 19.0
# >>> average = 18.0
# >>> average = 19.0
# >>> average = 18.0
  • if you need to modify one/both of the input lists, next to the zip operator into enumerate
  • e.g. in 1052. Grumpy Bookstore Owner you need to set the value of input1 to 0 if the value of the corresponding input2 is 1
🠋 needs to be set to 0 
input1 = [3, 5, 8]
input2 = [0, 0, 1]
  • the combination of zip and enumerate, with the index x used to modify the value looks as follows
for i, (value1, value2) in enumerate(zip(input1, input2)):
if value2 == 1:
input1[i] = 0

LINKS

--

--

No responses yet