There is a code. Logically should work, but no. When adding an element in a loop using the append() method append() it rewrites all the elements, and you need to save the results of each iteration. Tried and insert() , and set the function itself in the loop, it does not help. Code example:

 def time(lists, var): lists[0] = lists[0]+var return lists time_all = [] lst = [0,1,2,3,4] for i in range(5): time_all.append(time(lst, i)) lst = time_all[i] print(time_all) 

gives it:

[[10, 1, 2, 3, 4], [10, 1, 2, 3, 4], [10, 1, 2, 3, 4], [10, 1, 2, 3, 4], [10, 1, 2, 3, 4]]

but you must :

[[ 0, 1, 2, 3, 4], [1, 1, 2, 3, 4], [3, 1, 2, 3, 4], [6, 1, 2, 3, 4], [10, 1, 2, 3, 4]]

PS It is necessary lists. It is necessary to change one element in the cycle, but then it passes a series of checks and other elements can change.

    1 answer 1

    Your time_all does not consist of five different lists, but five copies of the same list! In other words - time_all consists of five links to the same element. You can check by adding print (time_all[0] is time_all[2]) at the end. The result will be true. Or change any item in any of the lists; it will change in all five:

     time_all[2][3] = 40 print time_all 

    Output: [[10, 1, 2, 40, 4], [10, 1, 2, 40, 4], [10, 1, 2, 40, 4], [10, 1, 2, 40, 4] , [10, 1, 2, 40, 4]]

    How to fix : you need not to attach an existing list (in this case the list is not attached, but simply create a link), but create a new one and attach it already.

    One of the options:

     for i in range(5): new_list = list(time(lst, i)) time_all.append(new_list) print(time_all) 

    Instead

     new_list = list(time(lst, i)) 

    can be used

     new_list = time(lst, i)[:] 
    • 2
      Instead of a single-line time_all = [list(time(lst, i)) for i in range(5)] : time_all = [list(time(lst, i)) for i in range(5)] - gil9red
    • it's bad when a function changes an argument and returns it. It would be possible to change the time() function (rename and return a new list) For example: add_to_head = lambda lst, value: [lst[0] + value] + lst[1:] without touching the input list - jfs