The idea is about merging iterables, which comes handy in many cases.
Working with zip function in Python is pretty neat and easy. It is a builtin - it is always available (unless overwritten by an assignment). We can convert the zip object to a tuple then to a string and write the string to the file: f.write(str(tuple(zip(list_1,list_2)))) In Python 3 there is no itertools.izip () as the zip () builtin behaves similarly.
The following will be the contents of the file:Īlso, there is a shorter code instead of using the for loop. Now close the file and check the saved data. List_2 = įinally, use the for loop to iterate through lists in zip function and write the result in the file (after converting a tuple to string): for i in zip(list_1, list_2): Now let’s create two lists to zip together.
If the file doesn’t exist, it will be created. Use the following line: f = open("zipOutput.txt", "a+") The first step is to open a file (we will use the append mode so nothing of existing content will be deleted). To save the output from the zip function into a file. That’s why we said before the length of the output equals the length of the smallest iterator, which is 2 in this case. Similarly, the second elements of all of them are joined together.īut there is no third element in the iterator y therefore, the third elements of remaining iterators are not included in the output object. The first elements of all of them are joined together. Syntax : zip (iterators) Parameters : Python iterables or containers ( list, string etc ) Return. It is used to map the similar index of multiple containers so that they can be used just using a single entity. In the above example, we defined three iterators of different lengths. Python zip () method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. are the iterator objects that we need to join using the zip function.Ĭonsider the following snippet, where we have three iterables and the zip function joins them together. In Python 3, izip() and imap() have been removed from itertools and. In the syntax above, the iterable0, iterable1, etc. To return an iterator, the izip() and imap() functions of itertools must be used. Iterables can be Python lists, dictionary, strings, or any iterable object. Syntax: zip(iterable0, iterable1, interable2, …) If the iterables in the zip function are not the same length, then the smallest length iterable decides the length of the generated output.
The zip function pairs the first elements of each iterator together, then pairs the second elements together and so on.