@@ -30,6 +30,72 @@ Python zip() built-in function
30
30
# The shelf costs $40
31
31
```
32
32
33
- <!-- remove this tag to start editing this page -->
34
- <empty-section />
35
- <!-- remove this tag to start editing this page -->
33
+ ## Other Usecases
34
+
35
+ The zip function in Python merges multiple iterables into tuples.
36
+
37
+ ``` python
38
+ # Combining three lists
39
+ >> > list1 = [1 , 2 , 3 ]
40
+ >> > list2 = [' a' , ' b' , ' c' ]
41
+ >> > list3 = [True , False , True ]
42
+
43
+ >> > zipped = zip (list1, list2, list3)
44
+ >> > print (list (zipped))
45
+ # Output: [(1, 'a', True), (2, 'b', False), (3, 'c', True)]
46
+ ```
47
+
48
+ ### Unzipping
49
+
50
+ ``` python
51
+
52
+ # Unzipping a zipped object
53
+ >> > zipped = [(1 , ' a' ), (2 , ' b' ), (3 , ' c' )]
54
+ >> > list1, list2 = zip (* zipped)
55
+ >> > print (list1)
56
+ # Output: (1, 2, 3)
57
+ >> > print (list2)
58
+ # Output: ('a', 'b', 'c')
59
+ ```
60
+
61
+ ## More Examples
62
+
63
+ ### Zipping with Different Lengths
64
+
65
+ zip stops creating tuples when the shortest iterable is exhausted.
66
+
67
+ ``` python
68
+ >> > numbers = [1 , 2 , 3 ]
69
+ >> > letters = [' a' , ' b' ]
70
+ >> >
71
+ >> > for num, letter in zip (numbers, letters):
72
+ ... print (f ' { num} -> { letter} ' )
73
+ # 1 -> a
74
+ # 2 -> b
75
+ ```
76
+
77
+ ### Using zip with Dictionaries
78
+
79
+ You can use zip to combine keys and values from two lists into a dictionary.
80
+
81
+ ``` python
82
+ >> > keys = [' name' , ' age' , ' city' ]
83
+ >> > values = [' Alice' , 25 , ' New York' ]
84
+ >> >
85
+ >> > my_dict = dict (zip (keys, values))
86
+ >> > print (my_dict)
87
+ # {'name': 'Alice', 'age': 25, 'city': 'New York'}
88
+ ```
89
+
90
+ ### Using zip with List Comprehensions
91
+
92
+ You can use zip in list comprehensions for more concise code.
93
+
94
+ ``` python
95
+ >> > list1 = [1 , 2 , 3 ]
96
+ >> > list2 = [4 , 5 , 6 ]
97
+ >> >
98
+ >> > summed = [x + y for x, y in zip (list1, list2)]
99
+ >> > print (summed)
100
+ # [5, 7, 9]
101
+ ```
0 commit comments