zip() and enumerate() in Python

Original link: https://blog.aeilot.top/2023/08/11/python-zip-enumerate/

Recently, I want to use Python to do some small projects and record some learning experience. And if this blog does not update technical articles, it will become a literary blog, which is obviously contrary to the original intention ()

zip()

zip() function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return an object composed of these tuples.

 1
2
3
4
5
6
7
8
 >>> 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 way to apply this is when traversing, you can traverse multiple arrays at the same time:

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

If the lengths of the arrays are not equal, the shortest length will prevail.

If you want to follow the longest length, you can use another function zip_longest() , so I won’t go into details.

enumerate()

enumerate() function is used to combine a traversable data object (such as a list, tuple, or string) into an index sequence, listing the data and the index at the same time.

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

This can also be used while traversing.

Precautions

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

This article is transferred from: https://blog.aeilot.top/2023/08/11/python-zip-enumerate/
This site is only for collection, and the copyright belongs to the original author.