Python has a number of built-in functions that allow coders to loop through data. Python’s zip() function allows you to iterate in parallel over two or more iterables. A simple example is helpful to understand the Python zip function. Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. Unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value. In Python 2, zip merges the lists into a list of tuples. The zip built-in function can iterate over multiple iterators at the same time. Specifically, let's examine a situation where you have a group of men and a group of women, and you want to pair them together for duo dance lessons. This means that the length of the output of the Python zip function will be equal to the length of its smallest argument. Here’s an example with three iterables: Here, you call the Python zip() function with three iterables, so the resulting tuples have three elements each. Leave a comment below and let us know. If you need to loop over multiple lists at the same time, use zip. num = [1, 2, 3] color = ['red', 'while', 'black'] value = [255, 256] for (a, b, c) in itertools.zip_longest (num, color, value): print (a, b, c) Output: 1 red 255 2 while 256 3 black None. One of the main purposes of the Python zip function is the ability to iterate over multiple objects simultaneously. This will run through the iterator and return a list of tuples. Consider you have two lists, and you instead want them to be one list, where elements from the shared index are together. Zip and for loop to iterate over two lists in parallel. Once you understand the power of for loops … You could also try to force the empty iterator to yield an element directly. It produces the same effect as zip() in Python 3: In this example, you call itertools.izip() to create an iterator. Any experienced Python programmer will know how zip works in a loop. In Python 2, zip() returns a list of tuples. Let’s look at a simple python zip function example. Python’s zip() function can take just one argument as well. With no arguments, it returns an empty iterator. Curated by the Real Python team. These are all ignored by zip() since there are no more elements from the first range() object to complete the pairs. However, for other types of iterables (like sets), you might see some weird results: In this example, s1 and s2 are set objects, which don’t keep their elements in any particular order. The reason why there’s no unzip() function in Python is because the opposite of zip() is… well, zip(). This means that the tuples returned by zip() will have elements that are paired up randomly. It is commonly used to loops over multiple data structures at once, without having to create nested loops. To do this, you can use zip() along with .sort() as follows: In this example, you first combine two lists with zip() and sort them. The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.. You can also update an existing dictionary by combining zip() with dict.update(). With sorted(), you’re also writing a more general piece of code. Note: If you want to dive deeper into Python for loops, check out Python “for” Loops (Definite Iteration). If the password is incorrect, an exception will be generated. The iterator stops when the shortest input iterable is exhausted. I will demonstrate this capability in this section. Python's for loops don't work the way for loops do in other languages. You can generalize this logic to make any kind of complex calculation with the pairs returned by zip(). It returns an iterator that can generate tuples with paired elements from each argument. In the first example, how the Python zip function can combine two lists into one zip object whose elements are each tuples of length 2. In Python 3.6 and beyond, dictionaries are ordered collections, meaning they keep... Unzipping a Sequence. Python’s zip() function combines the right pairs of data to make the calculations. Unsubscribe any time. In this tutorial, you’ll discover the logic behind the Python zip() function and how you can use it to solve real-world problems. In these cases, the number of elements that zip() puts out will be equal to the length of the shortest iterable. In this tutorial, I will show you how to use the Python zip function to perform multiple iterations over parallel data structures. Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas: Real Python Comment Policy: The most useful comments are those written with the goal of learning from or helping out other readers—after reading the whole article and all the earlier comments. The first iteration is truncated at C, and the second one results in a StopIteration exception. Share The zip function iterates through multiple iterables, and aggregates them. Mark as Completed Introduction Python is a very high-level programming language, and it tends to stray away from anything remotely resembling internal data structure. You can also use sorted() and zip() together to achieve a similar result: In this case, sorted() runs through the iterator generated by zip() and sorts the items by letters, all in one go. 2. The result will be an iterator that yields a series of 1-item tuples: This may not be that useful, but it still works. If you take advantage of this feature, then you can use the Python zip() function to iterate through multiple dictionaries in a safe and coherent way: Here, you iterate through dict_one and dict_two in parallel. Here's what this loops like: You'll notice that this returns a special zip object, so the output of this code will look like this: To transform this zip object into a human-readable format, you can use one of Python's built-in data structure functions. It is possible because the zip function returns a list of tuples, where the ith tuple gets elements from the ith index of every zip argument (iterables). The iteration will continue until the longest iterable is exhausted: Here, you use itertools.zip_longest() to yield five tuples with elements from letters, numbers, and longest. The function takes in iterables as arguments and returns an iterator. ', 3), ('? The length of the resulting tuples will always equal the number of iterables you pass as arguments. This lets you iterate through all three iterables in one go. We’ll also see how the zip() return type is different in Python 2 and 3. zip() Function in Python 3.x. By the end of this tutorial, you’ll learn: Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level. In Python 3, zip does basically the same thing, but instead it returns an iterator of tuples. In this case, you can use dict() along with zip() as follows: Here, you create a dictionary that combines the two lists. In fact, this visual analogy is perfect for understanding zip(), since the function was named after physical zippers! It should be of no surprise, then, that we can use tuple and dict to return tuples and dictionaries. Often we have to loop over two iterables at the same time. With this trick, you can safely use the Python zip() function throughout your code. Just like we can pass in different data structures as arguments of the Python zip function, it is possible to export different data types as well. The iteration ends with a StopIteration exception once the shortest input iterable is exhausted. Usage in Python. To do this, call the values method on the dictionary objects when you pass them into the zip function. Now it’s time to roll up your sleeves and start coding real-world examples! If you use dir() to inspect __builtins__, then you’ll see zip() at the end of the list: You can see that 'zip' is the last entry in the list of available objects. Looping over multiple iterables 1. zip() can provide you with a fast way to make the calculations: Here, you calculate the profit for each month by subtracting costs from sales. Here is the source code for the Python zip function: We will explore more of the characteristics and functionality of the Python zip function throughout the rest of this tutorial. For loops. for statement in Python. The Python zip function is an important tool that makes it easy to group data from multiple data structures. The Python zip () function accepts iterable items and merges them into a single tuple. Zip is a great functionality built right into Python. The above way of using else and continue may be difficult to understand unless you are familiar with Python.. You can pass lists, tuples, sets, or dictionaries through the zip () function. This approach can be a little bit faster since you’ll need only two function calls: zip() and sorted(). The resulting list is truncated to the length of the shortest input iterable. For example, suppose you retrieved a person’s data from a form or a database. Leodanis is an industrial engineer who loves Python and software development. If you are interested in the technical details, here is the official definition of the Python zip function from the official Python documentation website: Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. With a single iterable argument, it returns an iterator of 1-tuples. In Python, enumerate () and zip () are useful when iterating elements of iterable ( list, tuple, etc.) The missing elements from numbers and letters are filled with a question mark ?, which is what you specified with fillvalue. Regardless, we’d do something like the following: Add a flag variable. The resultant value is a zip object that stores pairs of iterables. What do you think the output of this code will be? You can call zip() with no arguments as well. If you really need to write code that behaves the same way in both Python 2 and Python 3, then you can use a trick like the following: Here, if izip() is available in itertools, then you’ll know that you’re in Python 2 and izip() will be imported using the alias zip.