0

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?

4
Contributors
6
Replies
36
Views
2 Years
Discussion Span
Last Post by sneekula
Featured Replies
  • 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) Read More

0

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.

0

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!

0

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 by vegaseat

0

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)
0

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?)

1

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.