YouTip LogoYouTip

Python Func Zip

# Python2.x Python zip() Function [![Image 3: Python Built-in Functions](#) Python Built-in Functions](#) * * * ## Description The **zip()** function takes iterables as arguments, packs corresponding elements from the objects into tuples, and returns a list composed of these tuples. If the number of elements in each iterator is inconsistent, the returned list length will be the same as the shortest object. Using the * operator, the tuples can be unpacked into a list. > The zip method differs between Python 2 and Python 3: In Python 3.x, to reduce memory usage, zip() returns an object. To display a list, you need to manually convert it using list(). > > > If you need to learn about Python 3 applications, you can refer to [Python3 zip()](#). ## Syntax zip syntax: zip([iterable, ...]) Parameter Description: * iterable -- One or more iterables; ## Return Value Returns a list of tuples. ## Examples The following two examples demonstrate the usage of zip in **Python2.x** and **Python3.x** respectively: ## Example (Python 2.0+) >>> a =[1,2,3] >>> b =[4,5,6] >>> c =[4,5,6,7,8] >>> zipped =zip(a,b)# Packed into a list of tuples [(1,4),(2,5),(3,6)] >>>zip(a,c)# Element count matches the shortest list [(1,4),(2,5),(3,6)] >>>zip(*zipped)# Opposite of zip, *zipped can be understood as unpacking, returns a 2D matrix-like structure [(1,2,3),(4,5,6)] ## 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))# Element count matches the shortest list [(1,4),(2,5),(3,6)] >>> a1, a2 =zip(*zip(a,b))# Opposite of zip, zip(*) can be understood as unpacking, returns a 2D matrix-like structure >>>list(a1) [1,2,3] >>>list(a2) [4,5,6] >>> [![Image 4: Python Built-in Functions](#) Python Built-in Functions](#)
← Python Func __Import__Python Func Hasattr β†’