Home > Mobile >  Create groups of N items from a list?
Create groups of N items from a list?

Time:01-06

There is a list with many items. Below is just an example:

example = ['Ireland',
 '324',
 '437',
 'Germany',
 '376',
 '431',
 'Canada',
 '387',
 '231']

How to create a tuple with N items each, so it becomes:

[('Ireland', '324', '437'),
 ('Germany', '376', '431'),
 ('Canada', '387', '231')]

I am trying to find different ways to do that, to better understand the language.

I have done it so far with this:

[x for x in zip(*[iter(example)]*3)]

How else could that be done while using only built-in functions?

CodePudding user response:

Try:

[tuple(example[i:i 3]) for i in range(0, len(example)-2, 3)]

However, if the list length is not a multiple of 3, items will be missed out.

As a side note, your answer can be shortened to

list(zip(*[iter(example)]*3))

instead of using [x for x in iter].

CodePudding user response:

list comprehension can help,

>>> example = ['Ireland',
...  '324',
...  '437',
...  'Germany',
...  '376',
...  '431',
...  'Canada',
...  '387',
...  '231']
>>> n=3
>>> [tuple(example[i:i n]) for i in range(0, len(example), n)]
[('Ireland', '324', '437'), ('Germany', '376', '431'), ('Canada', '387', '231')]

If the length of the list is not a multiple of n, you will end up last tuple with less than n items. Quick hack is to fill the input list with some values to make it's length a multiple of n.

  •  Tags:  
  • Related