Binary element list grouping in Python

When working with lists of pairs, you often need to group elements by a common value. Python provides several approaches to group sublists based on shared elements, typically grouping by the second element of each pair.

Using set and map

This approach extracts unique second elements using set() and map(), then groups first elements that share the same second element ?

days_data = [['Mon', 2], ['Tue', 3], ['Wed', 3],
             ["Thu", 1], ['Fri', 2], ['Sat', 3],
             ['Sun', 1]]

# Extract unique second elements
unique_values = set(map(lambda i: i[1], days_data))

# Group first elements by second element
result = [[j[0] for j in days_data if j[1] == i] for i in unique_values]

print("The grouped elements are:")
for group in result:
    print(group)
The grouped elements are:
['Thu', 'Sun']
['Mon', 'Fri']
['Tue', 'Wed', 'Sat']

Using groupby and itemgetter

The itemgetter function extracts the second element for sorting and grouping. This method maintains the order of groups ?

from itertools import groupby
from operator import itemgetter

days_data = [['Mon', 2], ['Tue', 3], ['Wed', 3],
             ["Thu", 1], ['Fri', 2], ['Sat', 3],
             ['Sun', 1]]

# Sort by second element first (required for groupby)
days_data.sort(key=itemgetter(1))

# Group by second element
groups = groupby(days_data, itemgetter(1))
result = [[item[0] for item in group] for (key, group) in groups]

print("The grouped elements are:")
for group in result:
    print(group)
The grouped elements are:
['Thu', 'Sun']
['Mon', 'Fri']
['Tue', 'Wed', 'Sat']

Using defaultdict

The defaultdict automatically creates lists for new keys, making it easy to collect grouped elements ?

from collections import defaultdict

days_data = [['Mon', 2], ['Tue', 3], ['Wed', 3],
             ["Thu", 1], ['Fri', 2], ['Sat', 3],
             ['Sun', 1]]

# Group using defaultdict
grouped = defaultdict(list)
for item in days_data:
    grouped[item[1]].append(item[0])

# Convert to list of lists
result = list(grouped.values())

print("The grouped elements are:")
for group in result:
    print(group)
print("\nAs dictionary:")
print(dict(grouped))
The grouped elements are:
['Mon', 'Fri']
['Tue', 'Wed', 'Sat']
['Thu', 'Sun']

As dictionary:
{2: ['Mon', 'Fri'], 3: ['Tue', 'Wed', 'Sat'], 1: ['Thu', 'Sun']}

Comparison

Method Time Complexity Memory Usage Maintains Order
set + map O(n²) Low No
groupby O(n log n) Low Yes (sorted)
defaultdict O(n) Medium Insertion order

Conclusion

Use defaultdict for best performance and natural grouping. Use groupby when you need sorted groups. The set + map approach works well for small datasets but has higher time complexity.

Updated on: 2026-03-15T18:08:47+05:30

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements