When two lists of different size are passed to the zip function the iterator of tuples returned stops when the shortest list is exhausted. What happens if we remove one element from the second list? > cities = Now, let’s see another example of how to use the zip function. ![]() Python Zip Function Applied to Lists of Different Length It allows to refer to each item in every tuple directly without having to access the elements of each tuple by index. You can also use the following approach with a for loop: > for city, country in zip(cities, countries): The result is the same when Python zip is applied to three lists or more. > countries = Īs mentioned before the zip object returned is an iterator of tuples, let’s see if we can iterate through it… > for value in zip(cities, countries):Īs you can see each item returned by the iterator is a tuple where the first element comes from the first list and the second element comes from the second list. It can be a bit abstract if just explained this way, let’s see how it works in practice when applied to two lists. The Python zip() function aggregates items from multiple iterables and returns an iterator of tuples. ![]() Conclusion Python Zip Function Applied to Two Lists.Using the Zip Function with Python Sets.Using the Zip Function with Two Strings.Can You Use the Zip Function With Different Data Types?.Python Zip Function Applied to Lists of Different Length. ![]() Python Zip Function Applied to Two Lists.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |