Zip Function
April 1, 2018
Sometimes, you may be passed two data separate data structures that have related information.
A simple example could be a list of grades on an exam in alphabetical order of students' names and another list of the student's names.
Because these two are related, we ought to put them in a single data structure.
One way to easily do this is use the built-in Python function called zip
. This function takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence.
This result is a zip object. We'll explain this concept later.
If we want to see our result in a list, we can use Python's built-in list
function and pass in this zip object.
We're returned a list of tuples in which each tuple contains the name of the student and their grade on the exam.
Alternatively, we can loop over the elements in our zip object.
Each tuple contains the name of the student and their grade on the exam.
We can also use tuple assignment in a for
loop to extract the elements in each tuple.
Notice how we assigned the variable name
to the first item in each tuple and grade
to the second item.
Then, we printed a string that uses these two variables to explain their relevance.
The zip object (that we returned above) is an iterator, which is any object that iterates through a sequence.
Iterators are similar to lists in some ways; but unlike lists, you can't use an index to select an element from an iterator.
Reference : https://dfrieds.com/python/zip-function.html
Last updated