Hello friends.
I want to create a list of sublists
E.G.

i = 0
pack = []
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
while i < 17:
    sublist = list[list[i]: list [i + 3]]
    pack = pack + sublist
    i += 1
print (pack)

the output is:
Type "copyright", "credits" or "license()" for more information.

================================ RESTART ================================

[0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 9, 8, 9, 10, 9, 10, 11, 10, 11, 12, 11, 12, 13, 12, 13, 14, 13, 14, 15, 14, 15, 16, 15, 16, 17, 16, 17, 18]

and I expected[[0,1,2], [1,2,3] ...etc...]
What is the think that i have missed?

If you add lists of integers together, you will always obtain a list of integers. If you want a list of sublist, you must append sublists to pack:

pack.append(sublist)

This adds only one element, this element is a sublist.

Avoid using Python function names like list for variable names.

if you use
list = [1, 2, 3]
and later
abc_list = list('abc')
it won't work!

You can study up on list comprehension ...

mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
size = 3
newlist = [mylist[n : n + size] for n in range(0, len(mylist), size)]
print(newlist)

''' result ...
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18]]
'''

Oops, sorry I see that this is not what you want.

Edited 1 Year Ago by vegaseat

Looks like you want this ...

mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
size = 3
newlist2 = [mylist[n : n + 3] for n in range(0, len(mylist)) if n < len(mylist)-size]
print(newlist2)

to gribouillis:
with .append the output is an error
with replacement of 0,1,2 by 'a','b','c' it's exactly the same problem, not due to item beyng integers or strings.
with the comprehension of lists, as indicated by @vegaseat, the python langage execute the sublisting (what is the rational of this appearent inconsistency, the big snake python do not folow human thinking?)

Apply append() this way:

i = 0
pack = []
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
while i < 17:
    sublist = mylist[i : i + 3]
    pack.append(sublist)
    i += 1
print (pack)
This question has already been answered. Start a new discussion instead.