Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python zip() Function

Python zip() Function

Python built-in function Python built-in function


Description

zip() The function takes iterable objects as arguments, packs the corresponding elements of the objects into tuples, and then returns a list of these tuples.

If the iterables have different lengths, the returned list has the same length as the shortest one; the * operator can be used to unpack the tuples back into lists.

The difference between the zip method in Python 2 and Python 3: in Python 3.x, to reduce memory usage, zip() returns an object. To display a list, you must convert it manually with list().

To learn about the Python 3 usage, you can refer to Python3 zip().

Syntax

zip syntax:


zip([iterable, ...])

Parameter Description:

Return Value

Returns a list of tuples.

Example

The following two examples demonstrate respectively Python2.x The difference between Python3.x how to use zip:

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

)

             

The number of elements matches the shortest list

[

(

1

,

4

)

,

(

2

,

5

)

,

(

3

,

6

)

]

zip

(

*zipped

)

         

As the opposite of zip, *zipped can be understood as unzipping, returning a two-dimensional matrix

[

(

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

<

zip

object

at

0x103abc288

list

(

zipped

)

 

Convert to a list with 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 opposite of zip, zip(*) can be understood as unpacking, returning a two-dimensional matrix form

list

(

a1

)

[

1

,

2

,

3

]

list

(

a2

)

[

4

,

5

,

6

]

Python built-in function Python built-in function