group an array in python

There are multiple ways to group a list/array in Python, and here are a couple of examples:

  1. Using itertools
main.py
import itertools

my_list = [1, 2, 3, 4, 5, 6]
grouped_list = [list(group) for key, group in itertools.groupby(my_list, lambda x: x//3)]
print(grouped_list)
157 chars
6 lines

Output:

main.py
[[1, 2, 3], [4, 5, 6]]
23 chars
2 lines
  1. Using List Comprehension
main.py
my_list = [1, 2, 3, 4, 5, 6]
n = 3
grouped_list = [my_list[i:i+n] for i in range(0, len(my_list), n)]
print(grouped_list)
122 chars
5 lines

Output:

main.py
[[1, 2, 3], [4, 5, 6]]
23 chars
2 lines

In both examples, a list of integers is grouped every 3 elements. The first example uses itertools.groupby to group consecutive elements based on the floor division by 3. The second example uses list comprehension to create sublists of length 3 using a range of indices.

gistlibby LogSnag