Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve groups of n items in list

In Python, how do I print every triple (or groups of n) items in a list?

I have searched and found various solutions using the itertools module for handling pairs, but I have failed to adapt them for groups of three. I will refrain from including my attempts here as I'm uncertain if they are at all indicative of the correct way to go.

Example:

my_list = ["abra", "cada", "bra", "hum", "dee", "dum"]

I would like to print the first triplet in one line, and then the next triplet on the next line:

"Abra cada bra"
"Hum dee dum"

Edit: In order to expand generality, the question has been edited to cover "groups of n items" instead of just triples.

like image 507
P A N Avatar asked Dec 04 '25 02:12

P A N


2 Answers

you could use straightforward for loop

i = 0
list = ["abra", "cada", "bra", "hum", "dee", "dum"]
while i < len(list):
  print(" ".join(list[i:i+3]))
  i += 3
like image 197
fl00r Avatar answered Dec 06 '25 15:12

fl00r


A list comprehension using indices is a fairly straightforward way of doing this.

print([my_list[i:i+3] for i in range(0, len(my_list), 3)])

or to print it as desired:

for i in range(0, len(my_list), 3):
    print(' '.join(list[i:i+3]))

Alternatively:

for t in zip(my_list[::3], my_list[1::3], my_list[2::3]):
    print(' '.join(t))
like image 34
Stuart Avatar answered Dec 06 '25 16:12

Stuart



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!