3 Learn Python to A.I Programming – Lesson
1. zip() in Python –
zip() is a built-in Python function that pairs elements from two or more iterables (lists, tuples, etc.) into grouped tuples
|
1 2 3 4 5 |
a = [1, 2, 3] b = ['a', 'b', 'c'] z = zip(a, b) print(list(z)) |
[(1, 'a'), (2, 'b'), (3, 'c')]
|
1 2 3 4 5 |
x = [10, 20, 30] y = [100, 200, 300] z = [1000, 2000, 3000] print(list(zip(x, y, z))) |
[(10, 100, 1000), (20, 200, 2000), (30, 300, 3000)]
|
1 2 3 4 5 |
names = ["Alice", "Bob", "Charlie"] ages = [24, 30, 19] for name, age in zip(names, ages): print(name, "is", age, "years old") |
Alice is 24 years old
Bob is 30 years old
Charlie is 19 years old
zip() with index (compare to normal loop)
for i in range(len(names)):
print(names[i], ages[i])
for name, age in zip(names, ages):
print(name, age)
|
1 2 3 4 |
a = [1, 2, 3, 4] b = ['x', 'y'] print(list(zip(a, b))) |
[(1, 'x'), (2, 'y')]
Because list b has only 2 elements.
Unzipping (reverse zip)
|
1 2 3 4 5 |
pairs = [(1, 'a'), (2, 'b'), (3, 'c')] numbers, letters = zip(*pairs) print(numbers) print(letters) |
(1, 2, 3)
('a', 'b', 'c')
using AI with zip
|
1 2 3 4 5 |
X = [(0,0), (0,1), (1,0), (1,1)] y = [0, 0, 0, 1] for (x1, x2), target in zip(X, y): print("Inputs:", x1, x2, "Target:", target) |
Inputs: 0 0 Target: 0
Inputs: 0 1 Target: 0
Inputs: 1 0 Target: 0
Inputs: 1 1 Target: 1