|
| 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