Is there another way to zip into a list?

When I want to zip something into a list, can I use something other than

list(zip(list_1, list_2))

or is that the only way?

Hey there @st_pr :slightly_smiling_face:

One could manually pair up each item in a pair of lists, put each pair in a tuple and then append that to a list, though this would not be very flexible.

To make it more flexible you could use a for loop to some extent and given two lists, pair each item from the first list up with an item from the second.

So in short the answer to your question would be yes, Python gives you all the tools needed to zip two lists(or more) without using the zip() function. In fact here is a simple way to do it, though if you would like to, I recommend challenging yourself to come up with a method.

Spoiler Alert
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']

zip1 = []
for index in range(len(list1)):
  zip1.append((list1[index], list2[index]))


Though this is not without its errors, if list1 has more elements than list2 you will end up with an index error. The use of a try/except could fix this.

I do have the question though, why do you want to do this without use of the zip()?


After an extra moment, I came up with this function using a try/except:

Spoiler Alert
list1 = ['a', 'b', 'c', 'd']
list2 = ['e', 'f', 'g']

def zipper(list1, list2):
  zipped = []
  for index in range(len(list1)):
      zipped.append((list1[index], list2[index]))
    except IndexError:
      print("'list1' has more elements than 'list2'...\nProcess terminated before all of 'list1' was paired:\n")
      return zipped

  return zipped

print(zipper(list1, list2))


It’s fine for me to use the zip() function but I just wanted to know if it was possible :slight_smile: