2

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?

Janmajay
  • 51
  • 6
  • 1
    You are running into this problem because your list `result` contains 3 copies of `list1`, not three separate lists. See here for more information: http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly?rq=1 – C_Z_ Dec 10 '15 at 19:31
  • Possible duplicate of [How to clone or copy a list in Python?](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) – Saeid Dec 10 '15 at 19:32

3 Answers3

7

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']]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
4

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])
Community
  • 1
  • 1
glibdud
  • 7,550
  • 4
  • 27
  • 37
0

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']]
Blair
  • 6,623
  • 1
  • 36
  • 42
  • Thank you! this works! But can you explain why was all_paths (now changed to "results" in the question) not storing desired lists in my code? – Janmajay Dec 10 '15 at 19:38