Reputation: 51
There are 2 given lists, suppose:
list1 = ['node1','node2','node3','node4']
list2 = ['goal1','goal2','goal3']
I require a list which returns:
result = [['node1','node2','node3','node4','goal1'],
['node1','node2','node3','node4','goal2'],
['node1','node2','node3','node4','goal3']]
Here is what I have:
result = []
for i in range (len(list2)):
list1.append(list2[i])
result.append(list1)
list1.pop()
The problem is, result is not being appended with the desired value. It prints,
[['node1', 'node2', 'node3', 'node4'],
['node1', 'node2', 'node3', 'node4'],
['node1', 'node2', 'node3', 'node4']]
after the for
loop is completed.
What am I doing wrong?
Upvotes: 2
Views: 96
Reputation: 180512
You can add list1
each goal to the end to list1 using a list comp:
list1 = ['node1', 'node2', 'node3', 'node4']
list2 = ['goal1', 'goal2', 'goal3']
print([list1 + [gl] for gl in list2])
Output:
[['node1', 'node2', 'node3', 'node4', 'goal1'],
['node1', 'node2', 'node3', 'node4', 'goal2'],
['node1', 'node2', 'node3', 'node4', 'goal3']]
Upvotes: 7
Reputation: 7880
What your loop is doing is repeatedly appending the same list object (list1
) to result
. You can verify that by doing something like list1.append(True)
after running the loop and checking result
again:
[['node1', 'node2', 'node3', 'node4', True],
['node1', 'node2', 'node3', 'node4', True],
['node1', 'node2', 'node3', 'node4', True]]
What you want to do is instead make a copy of list1
to append each time, such as:
for i in range (len(list2)):
list1.append(list2[i])
result.append(list(list1))
list1.pop()
Although I would probably instead make use of list concatenation, which implicitly makes a new list:
for item in list2:
result.append(list1 + [item])
Upvotes: 4
Reputation: 6693
You can fix this using extend
:
>>> for i in range(len(list2)):
tmp = []
tmp.extend(list1)
tmp.append(list2[i])
all_paths.append(tmp)
>>> all_paths
[['node1', 'node2', 'node3', 'node4', 'goal1'], ['node1', 'node2', 'node3', 'node4', 'goal2'], ['node1', 'node2', 'node3', 'node4', 'goal3']]
Upvotes: 0