Skip to content Skip to sidebar Skip to footer

Grouping Every Three Items Together In List - Python

I have a list consisting of a repeating patterns i.e. list=['a','1','first','b','2','second','c','3','third','4','d','fourth']` I am not sure how long this list will be, it could

Solution 1:

You can get the chunks using zip():

>>> lst = ['a','1','first','b','2','second','c','3','third','4','d','fourth']
>>> list(zip(*[iter(lst)]*3))
[('a', '1', 'first'), ('b', '2', 'second'), ('c', '3', 'third'), ('4', 'd', 'fourth')]

Using zip() avoids creating intermediate lists, which could be important if you have long lists.

zip(*[iter(lst)]*3) could be rewritten:

i = iter(lst)   # Create iterable from listzip(i, i, i)    # zip the iterable 3 times, giving chunks of the original list in 3

But the former, while a little more cryptic, is more general.

If you need names for this lists then I would suggest using a dictionary:

>>> d = {'list_{}'.format(i): e for i, e inenumerate(zip(*[iter(lst)]*3), 1)}
>>> d
{'list_1': ('a', '1', 'first'),
 'list_2': ('b', '2', 'second'),
 'list_3': ('c', '3', 'third'),
 'list_4': ('4', 'd', 'fourth')}
>>> d['list_2']
('b', '2', 'second')

Solution 2:

Try this

chunks = [data[x:x+3] for x in xrange(0, len(data), 3)]

It will make sublists with 3 items

Post a Comment for "Grouping Every Three Items Together In List - Python"