Wednesday, February 28, 2024

Combine related information using zip function

Example 1:

 # Example with three lists

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 22]
cities = ["New York", "San Francisco", "Los Angeles"]

# Using zip to combine the three lists
combined = zip(names, ages, cities)

# Converting the result to a list for printing
# Example with three lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 22]
cities = ["New York", "San Francisco", "Los Angeles"]

# Using zip to combine the three lists
combined = zip(names, ages, cities)

# Converting the result to a list for printing
result_list = list(combined)

# Output
print(result_list)
Output:
[('Alice', 25, 'New York'), ('Bob', 30, 'San Francisco'), 
('Charlie', 22, 'Los Angeles')]

Modified Example 1:

# Example with three lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 22]
cities = ["New York", "San Francisco", "Los Angeles"]

# Using zip to combine the three lists
combined = zip(names, ages, cities)

# Converting the result to a list for printing
# Example with three lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 22]
cities = ["New York", "San Francisco", "Los Angeles"]

# Using zip to combine the three lists
combined = zip(names, ages, cities)

for emp in combined:
print(f"Employee name: {emp[0]},
Employee Age: {emp[1]} and Work location is {emp[2]}")

Output:
Employee name: Alice, Employee Age: 25 and Work location is New York
Employee name: Bob, Employee Age: 30 and Work location is San Francisco
Employee name: Charlie, Employee Age: 22 and Work location is Los Angeles

No comments:

Post a Comment