-3

I want to make a list containing list of 4 elements and so on from a list of 100 elements without using numpy.

For suppose

x = [list containing numbers from 1 to 100]

I want to store these 100 elements in a manner that

y = [[1,2,3,4],[5,6,7,8].......[97,98,99,100]]

  • See also: [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Niko Föhr Jan 21 '21 at 16:50

3 Answers3

0

as already mentioned here

y = [x[i: i+4] for i in range(0, len(x), 4)]
Epsi95
  • 8,832
  • 1
  • 16
  • 34
0

This works:

def fillList(list):
    i = 1
    while i<=100:
        sublist = []
        for x in range(1,5):
            sublist.append(i)
            i = i + 1
        list.append(sublist)

l = []

fillList(l)

print(l)

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36], [37, 38, 39, 40], [41, 42, 43, 44], [45, 46, 47, 48], [49, 50, 51, 52], [53, 54, 55, 56], [57, 58, 59, 60], [61, 62, 63, 64], [65, 66, 67, 68], [69, 70, 71, 72], [73, 74, 75, 76], [77, 78, 79, 80], [81, 82, 83, 84], [85, 86, 87, 88], [89, 90, 91, 92], [93, 94, 95, 96], [97, 98, 99, 100]]
Jaysmito Mukherjee
  • 1,467
  • 2
  • 10
  • 29
0

Something like this should do it..

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
split_length = 4
my_split_list = [my_list[i:i + split_length] for i in range(0, len(my_list), split_length)]
print(my_split_list)
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50