# Define two lists list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] # Combine using zip zipped = zip(list1, list2) # Convert to a list of tuples zipped_list = list(zipped) print(zipped_list)
[(1, 'a'), (2, 'b'), (3, 'c')]
# Define two lists list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] # Combine using zip and iterate for number, letter in zip(list1, list2): print(f'Number: {number}, Letter: {letter}')
Number: 1, Letter: a Number: 2, Letter: b Number: 3, Letter: c
# Define lists of different lengths list1 = [1, 2, 3, 4] list2 = ['a', 'b'] # Combine using zip zipped_list = list(zip(list1, list2)) print(zipped_list)
[(1, 'a'), (2, 'b')]
# Define a list of tuples zipped_list = [(1, 'a'), (2, 'b'), (3, 'c')] # Unzip the list numbers, letters = zip(*zipped_list) print(numbers) print(letters)
(1, 2, 3) ('a', 'b', 'c')
# Define three lists list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] list3 = [10.1, 20.2, 30.3] # Combine using zip zipped_list = list(zip(list1, list2, list3)) print(zipped_list)
[(1, 'a', 10.1), (2, 'b', 20.2), (3, 'c', 30.3)]
# Define two dictionaries dict1 = {'name': 'Alice', 'age': 25} dict2 = {'name': 'Bob', 'age': 30} # Combine using zip zipped_dict = list(zip(dict1, dict2)) print(zipped_dict) # To zip dictionary values zipped_dict_values = list(zip(dict1.values(), dict2.values())) print(zipped_dict_values)
[('name', 'name'), ('age', 'age')] [('Alice', 'Bob'), (25, 30)]
# Define two lists list1 = [1, 2, 3] list2 = [4, 5, 6] # Compute the sum of pairs using list comprehension sum_list = [x + y for x, y in zip(list1, list2)] print(sum_list)
[5, 7, 9]