Iterating with the last item is repeated as the first in the next iteration
I have a list with objects:
oldList=[a,b,c,d,e,f,g,h,i,j,...]
I need to create a new list with nested list items that looks like this:
newList=[[a,b,c,d],[d,e,f,g],[g,h,i,j]...]
or just spoken - the last item from the previous nested list is the first item in the next new nested list.
source to share
One way to do this 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]
means that we print a chunk of 4 values, starting at positioni
-
range(0,len(l),3)
means we are crossing the length of the list by doing three jumps
So, the main work is that we take a chunk of 3 elements into the list, but we modify the length of the slice so that it includes an additional element. Thus, we can have a list of 4 elements.
Small note. Initialization oldList=[a,b,c,d,e,f,g,h,i,j,...]
is not valid if not previously been determined a
, b
, c
, d
, etc. You may have been looking foroldList = ['a','b','c','d','e','f','g','h','i','j']
Alternatively, if you want the solution to be split into even chunks, you can 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']]
source to share