How to Split a List of Tuples into Two Separate Lists in Python – 4 Simple Methods
This article demonstrates four practical ways to transform a list of (letter, number) tuples into two distinct lists—one for letters and one for numbers—using basic loops, zip unpacking, pandas, and numpy, complete with code snippets and output screenshots.
Problem
A fan in a Python community asked how to split a list of tuples like
[("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3), ("c", 1), ("c", 2), ("c", 3)]into two separate lists, one containing the first elements and the other containing the second elements.
Method 1 – Simple Loop
Iterate over the original list and append each component to its own list.
# coding:utf-8
letter_list = []
num_list = []
list1 = [('a',1),('a',2),('a',3),('b',1),('b',2),('b',3),('c',1),('c',2),('c',3)]
for i in list1:
letter_list.append(i[0])
num_list.append(i[1])
print(letter_list)
print(num_list)Method 2 – Zip Unpacking
Use zip(*list1) to transpose the list of tuples.
list1 = [('a',1),('a',2),('a',3),('b',1),('b',2),('b',3),('c',1),('c',2),('c',3)]
list_result = tuple(zip(*list1))
letter_list = list(list_result[0])
num_list = list(list_result[1])
print(letter_list)
print(num_list)A more concise form:
letter_list, num_list = zip(*list1)
print(letter_list)
print(num_list)Method 3 – pandas
Convert the list of tuples into a DataFrame and extract each column as a list.
import pandas as pd
list1 = [('a',1),('a',2),('a',3),('b',1),('b',2),('b',3),('c',1),('c',2),('c',3)]
df = pd.DataFrame(list1)
print(df[0].tolist())
print(df[1].tolist())Method 4 – numpy
Transform the list into a NumPy array and transpose it.
import numpy as np
list1 = [('a',1),('a',2),('a',3),('b',1),('b',2),('b',3),('c',1),('c',2),('c',3)]
letter_list, num_list = np.array(list1).T.tolist()
print(letter_list)
print(num_list)Conclusion
All four approaches correctly separate the original list into two lists; choose the one that best matches your project's dependencies and readability preferences.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
