Python zip()
method takes iterables like list, dictionary, etc., and aggregates them into a tuple which is returned as zip() method result. The zip() method is used to convert different iterables like list, dictionary, set, string, etc. into the tuple type by matching. The zip() method is provided a built-in method with Python and there is no need to install or load a module.
zip() Method Syntax
The zip() method has the following simple syntax where a single or more iterable can be provided as parameters.
zip(ITERABLES)
- ITERABLES is single or more iterables separated with command.
Convert List (Iterable) to Tuple
The list type is the most popular type used with the zip() method. We can provide two or more lists in order to match them one by one in a row. In the following example, we provide two lists of names countries and codes. The list countries stores country names and the list codes stores the country codes. We can match them one by one as a tuple. The first item in the countries list matched with the first item in the codes list.
countries = ["USA","UK","Turkey","Germany"]
codes = [0,1,2,3]
t = zip(countries,codes)
print(list(t))
[('USA', 0), ('UK', 1), ('Turkey', 2), ('Germany', 3)]
Convert Dictionary (Iterable) to Tuple
The dictionaries can be used to zip with dictionaries or lists. By default, the key is used for every item of the dictionary. In the following example, we use a single dictionary where the keys and values are provided as two iterable to the zip() method. The dictionary items are converted into tuples.
d={"a":1 , "b":2 , "c":3 , "d":4}
t = zip(d.keys,d.values)
print(list(t))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
Convert Two or More (Multiple) Iterables to Tuple
The zip() method is not only used for two iterables. We can use the zip() method 3 or more iterables where every item in the iterables are matches according to their index numbers and returned as a single tuple.
names = ["ismail","ahmet","elif"]
surnames = ["baydan","ali","ecrin"]
ages = [37,8,12]
persons = zip(names,surnames,ages)
print(list(persons))
[('ismail', 'baydan', 37), ('ahmet', 'ali', 8), ('elif', 'ecrin', 12)]