banner
满五

满五的博客

Non-Binary | High School | OI | Code | Photography | etc. 独立开发者、摄影/文学/电影爱好者 English/中文,日本語を勉強しています INFP | they
github
twitter_id
email

zip() and enumerate() in Python

zip()#

The zip() function is used to take iterables as arguments, pack the corresponding elements from each object into tuples, and then return an object composed of these tuples.

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [4, 5, 6]
>>> zipped = zip(a, b, c)
>>> zipped
<zip object at 0x00000278786975C0>
>>> list(zipped)
[(1, 4, 4), (2, 5, 5), (3, 6, 6)]

One application of this is to iterate through multiple arrays simultaneously:

>>> for i, j, k in zip(a, b, c):
...     print(i, j, k)
...
1 4 4
2 5 5
3 6 6

If the arrays are of unequal length, the shortest length will be used.

If you want to use the longest length, you can use another function called zip_longest(), but I won't go into detail here.

enumerate()#

The enumerate() function is used to combine a traversable data object (such as a list, tuple, or string) into an indexed sequence, while listing both the data and the index.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

This can also be used during iteration.

Notes#

When using these two functions, you need to import the itertools module, otherwise an error will occur.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.