zip()
names = ["Jenny", "Alex", "Sam", "Grace"]
heights = [61, 70, 67, 64]

If we wanted to create a nested list that paired each name with a height, we could use the built-in function zip().

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. This is how we would do it for our names and heights lists:

names_and_heights = zip(names, heights)

If we were to then examine this new variable names_and_heights, we would find it looks a bit strange:

print(names_and_heights)

Would output:

<zip object at 0x7f1631e86b48>

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

converted_list = list(names_and_heights)
print (converted_list)

Outputs:

[('Jenny', 61), ('Alexus', 70), ('Sam', 67), ('Grace', 64)]

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).