1

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

I have list of tuples, each tuple has two items (the amount of tuples may vary).

[(a, b), (c, d)...)]

I want to convert the list to a nested list of tuples so that each nested list contains 4 tuples, if the original list of tuples has quantity not divisible by 4 e.g. 13 then the final list should contain the leftover amount in the case of 13, 1 tuple.

[[(a, b), (c, d), (e, f), (g, h)], [(a, b), (c, d), (e, f), (g, h)]...]

One of the things about python I love is the methods and constructs for converting between different data structures, I was hoping there might be such a method or construct for this problem that would be more pythonic then what Iv come up with.

    image_thumb_pairs = [(a, b), (c, d), (e, f), (g, h), (i, j)]
    row = []
    rows = []
    for i, image in enumerate(image_thumb_pairs):
        row.append(image)
        if(i+1) % 4 == 0:
            rows.append(row)
            row = []
    if row:
        rows.append(row) 
Community
  • 1
  • 1
volting
  • 16,773
  • 7
  • 36
  • 54

1 Answers1

2
>>> lst = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12), (13, 14), (15, 16), (17, 18)]
>>> [lst[i:i+4] for i in xrange(0, len(lst), 4)]
[[(1, 2), (3, 4), (5, 6), (7, 8)], [(9, 10), (11, 12), (13, 14), (15, 16)], [(17, 18)]]
Dave Kirby
  • 25,806
  • 5
  • 67
  • 84