One step list operation in Python
Question:
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]
Answers:
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)]
You can also use numpy arrays:
A = np.array([12,8,4,0])
sol = np.concatenate((A+1, A+2, A+3))
The output is [13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]
as expected.
with walrus operator :=
, you can achive this as
A=[12,8,4,0]
result = (B:= [i+1 for i in A]) + (C:= [i+1 for i in B]) + (D:= [i+1 for i in C])
print(result)
output
[13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]
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]
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)]
You can also use numpy arrays:
A = np.array([12,8,4,0])
sol = np.concatenate((A+1, A+2, A+3))
The output is [13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]
as expected.
with walrus operator :=
, you can achive this as
A=[12,8,4,0]
result = (B:= [i+1 for i in A]) + (C:= [i+1 for i in B]) + (D:= [i+1 for i in C])
print(result)
output
[13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]