Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping every three items together in list - Python [duplicate]

Tags:

python

list

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 be fairly long, but I want to create list of the repeating patters i.e. along with populated names

list_1=['a','1','first']
list_2=['b','2','second']
list_3=['c','3','third']
..... etc

What is the best, basic code (not requiring import of modules) that I can use to achieve this?

like image 819
user88720 Avatar asked Oct 15 '25 11:10

user88720


1 Answers

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 list
zip(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 in enumerate(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')
like image 86
AChampion Avatar answered Oct 18 '25 04:10

AChampion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!