Skip to content

Commit 9b6262e

Browse files
Create zip.md (yasoob#218)
* Create zip.md Create new file for 'zip' function * Converted to reStructured * added zip to the index Co-authored-by: M.Yasoob Ullah Khalid ☺ <yasoob.khld@gmail.com> Co-authored-by: Yasoob Khalid <hi@yasoob.me>
1 parent 0bc5da8 commit 9b6262e

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ Table of Contents
5050
virtual_environment
5151
collections
5252
enumerate
53+
zip
5354
object_introspection
5455
comprehensions
5556
exceptions

zip.rst

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
Zip and unzip
2+
-------------
3+
4+
**Zip**
5+
6+
Zip is a useful function that allows you to combine two lists easily.
7+
8+
After calling zip, an iterator is returned. In order to see the content wrapped inside, we need to first convert it to a list.
9+
10+
Example:
11+
12+
.. code:: python
13+
14+
first_name = ['Joe','Earnst','Thomas','Martin','Charles']
15+
16+
last_name = ['Schmoe','Ehlmann','Fischer','Walter','Rogan','Green']
17+
18+
age = [23, 65, 11, 36, 83]
19+
20+
print(list(zip(first_name,last_name, age)))
21+
22+
# Output
23+
#
24+
# [('Joe', 'Schmoe', 23), ('Earnst', 'Ehlmann', 65), ('Thomas', 'Fischer', 11), ('Martin', 'Walter', 36), ('Charles', 'Rogan', 83)]
25+
26+
One advantage of zip is that it improves readability of for loops.
27+
28+
For example, instead of needing multiple inputs, you only need one zipped list for the following for loop:
29+
30+
.. code:: python
31+
32+
first_name = ['Joe','Earnst','Thomas','Martin','Charles']
33+
last_name = ['Schmoe','Ehlmann','Fischer','Walter','Rogan','Green']
34+
age = [23, 65, 11, 36, 83]
35+
36+
for first_name, last_name, age in zip(first_name, last_name, age):
37+
print(f"{first_name} {last_name} is {age} years old")
38+
39+
# Output
40+
#
41+
# Joe Schmoe is 23 years old
42+
# Earnst Ehlmann is 65 years old
43+
# Thomas Fischer is 11 years old
44+
# Martin Walter is 36 years old
45+
# Charles Rogan is 83 years old
46+
47+
**Unzip**
48+
49+
We can use the `zip` function to unzip a list as well. This time, we need an input of a list with an asterisk before it.
50+
51+
The outputs are the separated lists.
52+
53+
Example:
54+
55+
.. code:: python
56+
57+
full_name_list = [('Joe', 'Schmoe', 23),
58+
('Earnst', 'Ehlmann', 65),
59+
('Thomas', 'Fischer', 11),
60+
('Martin', 'Walter', 36),
61+
('Charles', 'Rogan', 83)]
62+
63+
first_name, last_name, age = list(zip(*full_name_list))
64+
print(f"first name: {first_name}\nlast name: {last_name} \nage: {age}")
65+
66+
# Output
67+
68+
# first name: ('Joe', 'Earnst', 'Thomas', 'Martin', 'Charles')
69+
# last name: ('Schmoe', 'Ehlmann', 'Fischer', 'Walter', 'Rogan')
70+
# age: (23, 65, 11, 36, 83)
71+

0 commit comments

Comments
 (0)