Skip to content

Increment of every element in list of lists with keeping the shape of the original list [closed]

I have a list for example: [[1,2,3],[2,4],[3,5],[4,6,7]] I want to have ten repeats of the list, and every element increase by 1 than the previous element like: [[1,2,3],[2,4],[3,5],[4,6,7],[2,3,4],[3,5],[4,6],[5,7,8]................40 elements(lists)]

Answer

You can do this with a nested list comprehension:

>>> a = [[1,2,3],[2,4],[3,5],[4,6,7]]
>>> [[y+i for y in x] for i in range(10) for x in a]
[[1, 2, 3], [2, 4], [3, 5], [4, 6, 7], [2, 3, 4], [3, 5], [4, 6], [5, 7, 8], [3, 4, 5], [4, 6], [5, 7], [6, 8, 9], [4, 5, 6], [5, 7], [6, 8], [7, 9, 10], [5, 6, 7], [6, 8], [7, 9], [8, 10, 11], [6, 7, 8], [7, 9], [8, 10], [9, 11, 12], [7, 8, 9], [8, 10], [9, 11], [10, 12, 13], [8, 9, 10], [9, 11], [10, 12], [11, 13, 14], [9, 10, 11], [10, 12], [11, 13], [12, 14, 15], [10, 11, 12], [11, 13], [12, 14], [13, 15, 16]]

The outermost iteration is for i in range(10), which takes you through the ten values of i that will be added to the elements of a. The next level for x in a iterates over the elements of a as x. The inner list comprehension [y+i for y in x] is what increments each x by i.