3

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.

P A N
  • 5,642
  • 15
  • 52
  • 103

4 Answers4

2

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
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • 1
    Keep in mind not to name a variable like a data type. So the list `list` should rather be named something like `l` instead of `list`. – albert Aug 29 '15 at 08:55
2

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))
Stuart
  • 9,597
  • 1
  • 21
  • 30
2

Try:

l1 = iter(list)
print '\n'.join([ ' '.join(x) for x in zip(*[l1]*3) ])
sureshvv
  • 4,234
  • 1
  • 26
  • 32
1

If you want an itertools answer:

from itertools import islice

my_list = ["abra", "cada", "bra", "hum", "dee", "dum"]
it = iter(my_list)
for sli in iter(lambda:list(islice(it, 3)), []):
    print("".join(sli))

Or using zip and iter:

my_list = ["abra", "cada", "bra", "hum", "dee", "dum"]
it = iter(my_list)
for sli in zip(it,it,it):
    print("".join(sli))

If you want to number each match and format:

n = 3
it = iter(my_list)
rn = map(str, range(1, n+1))
for sli in zip(it, it, it):
    print(" ".join(["{}: {}".format(a,b) for a,b in zip(rn, sli)]))

Output:

1: abra 2: cada 3: bra
1: hum 2: dee 3: dum

For grouping an arbitrary number of elements, there is the grouper recipe from itertools:

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

for grp in (grouper(my_list,3)):
    print("".join(grp))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thanks for including these alternatives! I have accepted this answer as it covers some situations I may have to deal with. But for future readers, I should mention that the `for loop` solutions below may just as well be the simplest solutions. – P A N Aug 29 '15 at 09:26
  • No worries, you tagged itertools so I provided some itertools solutions, using iter and zip would still probably be better than the for loop and slicing though – Padraic Cunningham Aug 29 '15 at 09:28