Grouping Adjacent Elements in Python

share link

by vigneshchennai74 dot icon Updated: Feb 22, 2023

technology logo
technology logo

Guide Kit Guide Kit  

If you need to group adjacent elements in an iterable equal to each other, the group_adjacent function can be a useful tool. This function uses the groupby function from the itertools module to group the elements of the iterable based on whether they are adjacent and equal to each other. 

For example, if you have a list of integers [1,2,2,3,3,3,4], calling group_adjacent on this list will return [1, [2, 2], [3, 3, 3], 4]. This can be useful if you must perform operations on groups of adjacent elements in the iterable. 

By returning a list with the groups of adjacent elements either as a single element or as a list, depending on their length, this function allows you to work with the data flexibly and intuitively. For example, you could use this function's output to calculate each group's length, perform operations on each group, or further process the data in other ways. 

Overall, this code can be a useful tool for anyone working with iterables containing adjacent elements that must be grouped together. 

Preview of the output that you will get on running this code from your IDE


In this solution we have used itertools.groupby to group everything into lists of adjacent identical values.

  1. Copy the code using the "Copy" button above, and paste it in a Python file in your IDE
  2. Run the file to get a nested list

I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.

I found this code snippet by searching for "Python creating nested lists" in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  • The solution is created and tested in Vscode 1.75.1 version
  • The solution is created in Python 3.7.15 Version

Using this solution, we can able to create a new nested list in python using group by function of itertools . This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would create a nested list in Python.


  • For any support on kandi solution kits, please use the chat
  • For further learning resources, visit the Open Weaver Community learning page.