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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With