1

I'm trying to create a list of list in python:

[[0, 1, 2], [4, 5, 6], [8, 9, 10], [11, 12]]

but my function doesn't append the last list ([11,12])

a = [a for a in list(range(13))]
print(a)
final_list = []
b =[]
for num in a:
    if len(b) <3:
        b.append(num)
    else:
        b = []

    if len(b) == 3:
        final_list.append(b)

print(final_list)

[[0, 1, 2], [4, 5, 6], [8, 9, 10]]
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
Papouche Guinslyzinho
  • 4,477
  • 8
  • 43
  • 82

2 Answers2

2
# You don't need `a` to be a list here, just iterate the `range` object
for num in range(13):
    if len(b) < 3:
        b.append(num)
    else:
        # Add `b` to `final_list` here itself, so that you don't have
        # to check if `b` has 3 elements in it, later in the loop.
        final_list.append(b)

        # Since `b` already has 3 elements, create a new list with one element
        b = [num]

# `b` might have few elements but not exactly 3. So, add it if it is not empty
if len(b) != 0:
    final_list.append(b)

Also, check this classic question to know more about splitting a list into evenly sized chunks.

Community
  • 1
  • 1
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
1

Before you print(final_list), add these lines:

if len(b):
    final_list.append(b)

That will include that list with only 2 elements.

Brent Washburne
  • 11,417
  • 4
  • 51
  • 70