Built-in Functions

Zip

In Python, we have an assortment of built-in functions that allow us to build our programs faster and cleaner. One of those functions is zip(). The zip() function allows us to quickly combine associated data-sets without needing to rely on multi-dimensional lists. The zip() function takes two (or more) lists as inputs and returns an object that contains a list of pairs. Each pair contains one element from each of the inputs.

list1 = [1, 2, 3, 4, 5]
list2 = ["a", "b", "c", "d", "e"]
list1_and_list2 = zip(list1, list2)

output:
<zip object at 0x7f1631e86b48>

This zip object contains the location of this variable in our computer’s memory. it is fairly simple to convert this object into a useable list by using the built-in function list():

convert_to_list = list(list1_and_list2)
print(convert_to_list)

outputs:
[(1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e")]

Notice two things:

  1. Our data set has been converted from a zip memory object to an actual list (denoted by [ ])

  2. Our inner lists don’t use square brackets [ ] around the values. This is because they have been converted into tuples (an immutable type of list).

Last updated