Example 1: Basic Usage of zip
# Basic usage of zip
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
# Combining lists using zip
combined_data = zip(names, ages)
# Displaying the result
for name, age in combined_data:
print(f"Name: {name}, Age: {age}")
#clcoding.com
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
Example 2: Different Lengths in Input Iterables
# Zip with different lengths in input iterables
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30]
# Using zip with different lengths will stop at the shortest iterable
combined_data = zip(names, ages)
# Displaying the result
for name, age in combined_data:
print(f"Name: {name}, Age: {age}")
#clcoding.com
Name: Alice, Age: 25
Name: Bob, Age: 30
Example 3: Unzipping with zip
# Unzipping with zip
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
# Combining lists using zip
combined_data = zip(names, ages)
# Unzipping the result
unzipped_names, unzipped_ages = zip(*combined_data)
# Displaying the unzipped data
print("Unzipped Names:", unzipped_names)
print("Unzipped Ages:", unzipped_ages)
#clcoding.com
Unzipped Names: ('Alice', 'Bob', 'Charlie')
Unzipped Ages: (25, 30, 35)
Example 4: Using zip with Dictionaries
# Using zip with dictionaries
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
# Creating a dictionary using zip
person_dict = dict(zip(keys, values))
# Displaying the dictionary
print(person_dict)
#clcoding.com
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Example 5: Transposing a Matrix with zip
# Transposing a matrix using zip
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Using zip to transpose the matrix
transposed_matrix = list(zip(*matrix))
# Displaying the transposed matrix
for row in transposed_matrix:
print(row)
#clcoding.com
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
Example 6: Using zip with enumerate
# Using zip with enumerate
names = ["Alice", "Bob", "Charlie"]
# Combining with enumerate to get both index and value
indexed_names = list(zip(range(len(names)), names))
# Displaying the result
for index, name in indexed_names:
print(f"Index: {index}, Name: {name}")
#clcoding.com
Index: 0, Name: Alice
Index: 1, Name: Bob
Index: 2, Name: Charlie
0 Comments:
Post a Comment