sun qingyao sun qingyao - 2 months ago 9
Python Question

Creating a nested list with list comprehension in Python

Basically, I want to group items in a list. For example:


  1. For
    [1, 2, 3, 4, 5, 6]
    , I want
    [[1, 2, 3], [4, 5, 6]]

  2. For
    [1, 2, 3, 4, 5, 6, 7]
    , I want
    [[1, 2, 3], [4, 5, 6], [7]]



I know how to unnest nested lists, but I have no idea how to create a nested list.

Answer

You can use list comprehension with range and output slices of 3:

>>> l = [1, 2, 3, 4, 5, 6, 7]
>>> [l[i:i+3] for i in range(0, len(l), 3)]
[[1, 2, 3], [4, 5, 6], [7]]

>>> l = [1, 2, 3, 4, 5, 6]
>>> [l[i:i+3] for i in range(0, len(l), 3)]
[[1, 2, 3], [4, 5, 6]]

Range takes three arguments where first one is start of range, second is the end and third is step. If you're using Python 2 use xrange instead.