How to Split a List of Tuples in Python?

Estimated read time 2 min read

To split a list of tuples into separate lists of values, you can use list comprehension or a loop. Here’s an example using list comprehension:

my_list = [('a', 1), ('b', 2), ('c', 3)]

# Split the list of tuples into separate lists
letters, numbers = zip(*my_list)

print(letters)  # Output: ('a', 'b', 'c')
print(numbers)  # Output: (1, 2, 3)

In this example, we define a list of tuples my_list, where each tuple contains a letter and a number. We use the zip() function with the unpacking operator (*) to split the list of tuples into two separate lists of values, one for the letters and one for the numbers. The resulting lists are stored in the letters and numbers variables.

Alternatively, you can use a loop to extract the values from each tuple:

my_list = [('a', 1), ('b', 2), ('c', 3)]

# Split the list of tuples into separate lists
letters = []
numbers = []
for tuple in my_list:
    letters.append(tuple[0])
    numbers.append(tuple[1])

print(letters)  # Output: ['a', 'b', 'c']
print(numbers)  # Output: [1, 2, 3]

In this example, we use a for loop to iterate over each tuple in the list my_list, and extract the first and second elements using indexing. We append the first element to the letters list and the second element to the numbers list.

Either method should work for splitting a list of tuples into separate lists of values in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply