How to create a list of tuples in Python

Published on Aug. 22, 2023, 12:16 p.m.

To create a list of tuples in Python, you can use a combination of the zip() function, list comprehension, or the tuple() function. Here are some examples:

# Using zip() and a for loop:
my_list = ['apple', 'banana', 'cherry']
my_tuple = (1, 2, 3)
my_list_of_tuples = []
for i in range(len(my_list)):
    my_list_of_tuples.append((my_list[i], my_tuple[i]))
print(my_list_of_tuples)    # Output: [('apple', 1), ('banana', 2), ('cherry', 3)]

# Using zip() and list comprehension:
my_list = ['apple', 'banana', 'cherry']
my_tuple = (1, 2, 3)
my_list_of_tuples = [(i, j) for i, j in zip(my_list, my_tuple)]
print(my_list_of_tuples)    # Output: [('apple', 1), ('banana', 2), ('cherry', 3)]

# Using tuple() and list comprehension:
my_list = ['apple', 'banana', 'cherry']
my_tuple = (1, 2, 3)
my_list_of_tuples = [tuple(i) for i in zip(my_list, my_tuple)]
print(my_list_of_tuples)    # Output: [('apple', 1), ('banana', 2), ('cherry', 3)]

In the first example, we use a for loop to iterate through both lists, and use the append() method to add each tuple to a new list called my_list_of_tuples.

In the second example, we use list comprehension and the zip() function to create a list of tuples.

In the third example, we use list comprehension and the tuple() function to convert the zip output to tuples.

These examples demonstrate three different ways to achieve the same result, so you can choose the method that works best for your specific use case.

Tags:

related content