0

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.

nalzok
  • 14,965
  • 21
  • 72
  • 139

2 Answers2

2

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.

niemmi
  • 17,113
  • 7
  • 35
  • 42
1

I think you can do it in this way:

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

You could change the size of the sublist by changing the n. But in the above code, I use the target twice, I hope to find a way use the target once.

bwangel
  • 732
  • 1
  • 7
  • 12