YouTip LogoYouTip

Python3 Func Zip

# Python3.x Python3 zip() Function [![Image 3: Python3 Built-in Functions](#) Python3 Built-in Functions](#) * * * ## Description The **zip()** function takes iterables (like lists, tuples, strings, etc.) as arguments, aggregates corresponding elements from each iterable into tuples, and returns an object composed of these tuples. The benefit of doing this is that it saves a considerable amount of memory. We can use `list()` conversion to output a list. If the number of elements in each iterator is inconsistent, the length of the returned list will be the same as that of the shortest iterable. Using the `*` operator, we can unpack the tuples back into lists. > Note the difference between zip in Python 2 and Python 3: In Python 2.x, `zip()` returns a list. > > > If you need to understand its application in Python 2, please refer to [Python zip()](#). ## Syntax The zip syntax is: zip([iterable, ...]) Parameter description: * iterable -- An iterable object (like a list, tuple, string, etc.) ## Return Value Returns an object. ## Examples The following examples demonstrate the usage of zip: ## Example (Python 3.0+) >>> a =[1,2,3] >>> b =[4,5,6] >>> c =[4,5,6,7,8] >>> zipped =zip(a,b)# Returns an object >>> zipped >>>list(zipped)# list() converts to a list [(1,4),(2,5),(3,6)] >>>list(zip(a,c))# The number of elements matches the shortest list [(1,4),(2,5),(3,6)] >>> a1, a2 =zip(*zip(a,b))# The inverse of zip, zip(*) can be understood as unzipping, returning a 2D matrix-like structure >>>list(a1) [1,2,3] >>>list(a2) [4,5,6] >>> [![Image 4: Python3 Built-in Functions](#) Python3 Built-in Functions](#)
← Met Win BtoaVue Transitions β†’