0

I'm having a hell of a time printing out n elements at a time from a list of tuples of unknown length.

A deck of cards, for example:

a = [ ('2','c'), ('2','d'), ('2','h'), ('2','s'), ('3','c'), ('3','d'), ... ,('A',h'),('A','s') ]

The list in this example starts out at 52 length, but I am popping off elements. I want to print them out in groups of four (for this example), but I keep getting fouled up at the last group which can have fewer than four elements.

Expected output after popping off a bunch of cards is:

('2','c'), ('2','d'), ('2','h'), ('2','s')
('3','c'), ('3','d'), ('3','h'), ('3','s')
...
('J','c'), ('J','d'), ('J','h'), ('J','s')
('Q','c'), ('Q','d')
asgoth
  • 35,552
  • 12
  • 89
  • 98
Clay
  • 55
  • 1
  • 10
  • 1
    [This one](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) might come in handy – georg Jan 10 '13 at 21:37

2 Answers2

3

Simple:

a = [ ('2','c'), ('2','d'), ('2','h'), ('2','s'), ('3','c'), ('3','d'), ... ,('A','h'),('A','s') ]

for e in range(0, len(a), 4):
    for i in a[e:e+4]:
        print i,
    print
georg
  • 211,518
  • 52
  • 313
  • 390
sqreept
  • 5,236
  • 3
  • 21
  • 26
  • I can't believe I didn't try a nested for loop. It's obvious, in retrospect. Thanks for the swift reply. – Clay Jan 10 '13 at 21:56
0

add a check that says, if len(a)<4 then pop len(a)-1

ajon
  • 7,868
  • 11
  • 48
  • 86