I have a list A. I am generating a new list by adding 1 to every element of the previous list and at the end, getting a combined list B+C+D. Is there a one step way to do this?
A=[12,8,4,0]
B=[i+1 for i in A]
C=[i+1 for i in B]
D=[i+1 for i in C]
print(B+C+D)
The current and expected output is
[13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]
>Solution :
You can do it like this:
[i+j for i in range(1, 4) for j in A]
This produces:
[13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]
It can also be done with itertools.product, but in this case I don’t think it buys you much:
[i+j for i, j in itertools.product(range(1, 4), A)]