Welcome to part 8 of the intermediate Python programming tutorial series. In this part, we're going to talk about the built-in function: zip.
The zip
function iterates through multiple iterables, and aggregates them. Consider you have two lists, and you instead want them to be one list, where elements from the shared index are together. While simple, there are a few important notes to make when working with it!
We'll work with the following data:
x = [1,2,3,4] y = [7,8,3,2] z = ['a','b','c','d']
Let's first combine x
and y
:
for a,b in zip(x,y): print(a,b)
1 7 2 8 3 3 4 2
We can also do more than two:
for a,b,c in zip(x,y,z): print(a,b,c)
1 7 a 2 8 b 3 3 c 4 2 d
Do note, however, that zip
creates a zip object:
print(zip(x,y,z))
<zip object at 0x000001BDA0F31E08>
But you can convert it to a list or tuple:
print(list(zip(x,y,z)))
[(1, 7, 'a'), (2, 8, 'b'), (3, 3, 'c'), (4, 2, 'd')]
If you're just working with two lists...you can even do a dict
!
names = ['Jill','Jack','Jeb','Jessica'] grades = [99,56,24,87] d = dict(zip(names,grades)) print(d)
{1: 7, 2: 8, 3: 3, 4: 2}
{'Jeb': 24, 'Jack': 56, 'Jessica': 87, 'Jill': 99}
We can also combine zip
with list comprehension:
[print(a,b,c) for a,b,c in zip(x,y,z)]
1 7 a 2 8 b 3 3 c 4 2 d
Now, using zip, let's illustrate a potential issue that you might run into.
The main take-away is the difference between list comprehension, and a typical for loop. It can be very easy to just run through your old code, and change all for loops to list comprehension. If you were using bad practices, however, this can cause you some trouble! Let's see an example!
x = [1,2,3,4] y = [7,8,3,2] z = ['a','b','c','d'] [print(x,y,z) for x,y,z in zip(x,y,z)] print(x)
1 7 a 2 8 b 3 3 c 4 2 d [1, 2, 3, 4]
See how the var x
is still what we expect? What if we use a regular for loop?
x = [1,2,3,4] y = [7,8,3,2] z = ['a','b','c','d'] #[print(x,y,z) for x,y,z in zip(x,y,z)] for x,y,z in zip(x,y,z): print(x,y,z) print(x)
1 7 a 2 8 b 3 3 c 4 2 d 4
Our vars in the regular for loop are overwriting the originals, compared to the list comprehension, which does not.
Next up, we're going to talk more about generators!