0

I have a list in python that looks like that: [a,b,c,d,e,f,g,h,i]. I would like to convert this list to a list of lists (nested list). The second level of lists should contain four elements maximal. Therefore, the new list should look like that:

[
  [a,b,c,d],
  [e,f,g,h],
  [i],
]

Is there a pythonic way to do this? I will have to do this several times so I would be pleased if anybody knows a way of doing this without using hundreds of indexes.

Nick Lehmann
  • 598
  • 1
  • 7
  • 25
  • You need to use slices. Try something like `[a,b,c,d,e,f,g,h,i][4:4]` and see what it does. – nickie May 20 '14 at 21:18

1 Answers1

2

You can use a list comprehension, xrange, and Explain Python's slice notation:

>>> lst = ['a', 'b', 'c', 'd', 'e',' f', 'g',' h', 'i']
>>> n = 4  # Size of sublists
>>> [lst[x:x+n] for x in xrange(0, len(lst), n)]
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i']]
>>>
Community
  • 1
  • 1