Group List into Sublists in Python (3 Examples)

 

In this post, you’ll learn how to group a list into sublists in the Python programming language.

Here you have an overview:

Let’s dive into it!

 

Example Python List

We use the following Python list as a basis for this tutorial.

my_list =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Have a look at the previous Python output. We have created an example integer list that contains values from 1 to 10. What if we wanted to group these values by even or odd? Let’s see some examples of how to do so!

 

Example 1: Group List into Sublists Using Dictionary

In this first example, we will demonstrate how to group my_list into various sublists depending on the parity of the integer: even or odd. Take a look at the following code.

grouped_dict = {}
 
for item in my_list:
    key = item % 2  
    grouped_dict.setdefault(key, []).append(item)
 
grouped_list = list(grouped_dict.values())
print(grouped_list)
# [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]

In this method, we iterated over each item in my_list and determined the grouping key based on the condition item % 2, which determines if the number can be divided by 2 (if so, then it’s even).

The grouped_dict dictionary is used to store the sublists as values, with the grouping keys as dictionary keys. The setdefault() method is used to create a new empty list for each grouping key if it doesn’t already exist, and then we append the item to the corresponding key.

Finally, the dictionary is converted to a list and stored in grouped_list, which has two sublists: the odds and the evens.

 

Example 2: Group List into Sublists Using collections Module

This second example uses the defaultdict class from the collections module to group my_list into sublists. To do so, first, we will import the defaultdict class, as follows.

from collections import defaultdict

As shown in the previous Python output, we will utilize the defaultdict class from the collections module, which automatically initializes a new list for any missing key when accessed.

grouped_dict = defaultdict(list)
 
for item in my_list:
    grouped_dict[item % 2].append(item)
 
grouped_list = list(grouped_dict.values())
print(grouped_list)
# [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]

We have created a defaultdict object called grouped_dict with the default value set to an empty list. As we iterated over each item in my_list, we directly appended the item to the corresponding key in grouped_dict based on the grouping condition.

Finally, we converted the defaultdict object to the list called grouped_list, which contains the grouped sublists.

 

Example 3: Group List into Sublists Using List Comprehension

In this last example, we will use list comprehension to create two sublists from my_list. Take a look.

even_list = [num for num in my_list if num % 2 == 0]
odd_list = [num for num in my_list if num % 2 != 0]
 
grouped_list = [odd_list, even_list]
print(grouped_list)
# [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]

As you can see, in this code, we created two separate lists, even_list and odd_list. The first one is created using a list comprehension that filters the elements from my_list where the number modulo 2 is equal to 0, indicating even numbers.

The odd_list is created using a similar list comprehension, but this time filtering the elements where the number modulo 2 is not equal to 0, indicating odd numbers.

Finally, we created grouped_list as a list containing odd_list followed by even_list. The output is a list of lists, where the first sublist contains the odd numbers and the second sublist contains the even numbers.

 

Video, Further Resources & Summary

Do you need more explanations on how to group a list into sublists in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

 

The YouTube video will be added soon.

 

Furthermore, you could have a look at the related tutorials on Statistics Globe:

This post has shown how to group a list into sublists. Please tell me about it in the comments if you have further questions.

 

Paula Villasante Soriano Statistician & R Programmer

This page was created in collaboration with Paula Villasante Soriano. Please have a look at Paula’s author page to get more information about her academic background and the other articles she has written for Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top