![]() So for example we can add a fourth item to the list of animals so that it now contains: and on the other hand maintain the qty list unchanged. Now we should, however, note that the standard zip function does not work when we have lists or tuples with mismatched lengths i.e if one list is longer than the other. ![]() So ‘tiger ’ and ‘6’ will also be paired together in one tuple. This is also the case for the rest of the elements in both iterables. For instance ‘elephant’ and ‘4’ fall within the same index and therefore have been placed in the same tuple. We can see in the output that the zip function takes elements that fall in the same index from both lists and creates a tuple for each one of them. Now the Python list method list() takes sequence types and converts them to lists. In order to get the actual list values of the zip object, we need to convert the object to a list. Printing out the elements of a zipped object If we print out the variable zipped we will end up with a zip object in the console or terminal. We are going to call this object zipped and then to apply the zip function to the two lists that we just created we will need to use the word zip followed by a pair of parentheses and then pass both lists that we want to be zipped between the parentheses separated by a comma. In this case, we will need to create the two lists that we intend to zip together, and then create a variable that will store our new zipped object. Python zip is a built-in Python function that allows us to create an iterator of tuples by mapping together elements from iterable based on their index numbers.įor example, we can use the Python zip function to create another zip object that will combine elements from the two lists.
0 Comments
Leave a Reply. |