

To become more successful in coding, solve more real problems for real people. If you put the asterisk operator anywhere else, Python will think it’s multiplication and throw an error (best case) x = ,]Ĭoders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. set, list, tuple): x = ,]įinally, let me clarify one last thing: the asterisk operator is placed just before the iterable to be unpacked (not after it or anywhere else). To fix this, you have to convert the iterator object in the iterable you want (e.g. This is more efficient and more general-purpose - compared to creating a list and returning the list as a result. An iterator in Python is an object that contains a fixed number of elements and allows you to access each element in an ordered fashion (the next(iterator) function for an iterator). The result of the zip() function is an iterator.
#ZIP AND IZIP PYTHON ZIP#
You will quickly realize that the result of the zip function is neither a list nor a tuple: x = ,] (Don’t ask me why they didn’t use the format ‘(x)’ instead of ‘(x,)’.) What’s a Zip Object in Python? I hope that you now understand completely that this is not a bug in Python but only a tuple with a single element. Many students of my free email course stumbled upon it (join us if you want to continuously improve in Python - day after day). This strange output formatting caused some confusion. The default output of a tuple with one element x is (x,). Thus, the tuple has only a single element. Python still creates a tuple of the i-th elements - only that there is only one of those. Maybe you remember that I did this a few emails ago to trick you. # Can You Use Zip With a Single Argument?

Python simply ignores the remaining elements of the longer list. The rest of the article is about answering any question you may have regarding the zip() function. Puzzle: what will be the output of the last two print statements?
#ZIP AND IZIP PYTHON CODE#
This is the idea in the following code snippet: lst_1 = So you (almost) have your two original lists again! When you zip those together, you get the new list: You can unzip them by using the following trick: If you remove the outer bracket of the result (e.g., via the asterisk operator), you get the following three tuples: (1,4) Now you zip them together and get the new list: Examples are lists, sets, or tuples.īefore I’ll explain it slowly to you, try out the code in our interactive shell: Explanation You can unzip this list of tuples by calling zip(*list) using the unpacking (asterisk) operator *.Īn iterable is an object that contains elements over which you can iterate. The zip() function takes a number of iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple.
