Adding list elements in Python
Question:
I have lists D
and E
. I am adding element of E
to each element of D
. I present the current and expected outputs.
D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)):
for j in range(0,len(E)):
F=D[i]+E[j]
G.append(F)
print(G)
The current output is
[[0, 4], [1, 4]]
The expected output is
[[0, 4], [1, 5]]
Answers:
This works.
D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)):
for j in range(0,len(E)):
F=[D[i][0], D[i][0]+E[j][0]]
G.append(F)
print(G)
D=[[0],[1]]
E=[[4]]
G = []
for item in D:
for item_ in E:
F = [item[0], item[0] + item_[0]]
G.append(F)
print(G)
or by using itertools:
import itertools
D=[[0],[1]]
E=[[4]]
G=[]
for item, item_ in itertools.product(D, E):
F = [item[0], item[0] + item_[0]]
G.append(F)
print(G)
my approach for even longer lists:
D=[[0],[1]]
E=[[4],[5]]
G=[]
for i in range(len(D)):
for j in E:
for a in j:
G.append(D[i]+[a+i])
print(G)
This results in a list of all possible combinations between the elements of D and E. The code uses the length of the lists D and E to determine the number of iterations, so it can handle lists of any length without needing to modify the code.
I have lists D
and E
. I am adding element of E
to each element of D
. I present the current and expected outputs.
D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)):
for j in range(0,len(E)):
F=D[i]+E[j]
G.append(F)
print(G)
The current output is
[[0, 4], [1, 4]]
The expected output is
[[0, 4], [1, 5]]
This works.
D=[[0],[1]]
E=[[4]]
G=[]
for i in range(0,len(D)):
for j in range(0,len(E)):
F=[D[i][0], D[i][0]+E[j][0]]
G.append(F)
print(G)
D=[[0],[1]]
E=[[4]]
G = []
for item in D:
for item_ in E:
F = [item[0], item[0] + item_[0]]
G.append(F)
print(G)
or by using itertools:
import itertools
D=[[0],[1]]
E=[[4]]
G=[]
for item, item_ in itertools.product(D, E):
F = [item[0], item[0] + item_[0]]
G.append(F)
print(G)
my approach for even longer lists:
D=[[0],[1]]
E=[[4],[5]]
G=[]
for i in range(len(D)):
for j in E:
for a in j:
G.append(D[i]+[a+i])
print(G)
This results in a list of all possible combinations between the elements of D and E. The code uses the length of the lists D and E to determine the number of iterations, so it can handle lists of any length without needing to modify the code.