3

I have some list with objects looks like:

oldList=[a,b,c,d,e,f,g,h,i,j,...]

what I need is to create a new list with nested list items which will look like this:

newList=[[a,b,c,d],[d,e,f,g],[g,h,i,j]...]

or simply spoken - last element from previous nested is first element in next new nested list.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Rade Tomovic
  • 298
  • 2
  • 14

1 Answers1

5

One of the ways of doing it is

>>> l = ['a','b','c','d','e','f','g','h','i','j']
>>> [l[i:i+4] for i in range(0,len(l),3)]
[['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j'], ['j']]

Here :

  • l[i:i+4] implies that we print a chunk of 4 values starting from position i
  • range(0,len(l),3) implies that we traverse the length of the list by taking three jumps

So the basic working of this is that, we are taking a chunk of 3 elements from the list, but we are modifying the slice length so that it includes an additional element. In this way, we can have a list of 4 elements.

Small Note - The initialization oldList=[a,b,c,d,e,f,g,h,i,j,...] is invalid unless a,b,c,d,etc are previously defined. You were perhaps looking for oldList = ['a','b','c','d','e','f','g','h','i','j']

Alternatively, if you wanted a solution which would split into even sized chunks only, then you could try this code :-

>>> [l[i:i+4] for i in range(0,len(l)-len(l)%4,3)]
[['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j']]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140