-3

I was trying to do following operation on a list 2 times:

-> for each index i: arr[i] = d - arr[i] where d is maximum element in list
-> append the resultant list to another list 

My code:

arr = [5, -1, 4, 2, 0]
n = len(arr)
res = []
for _ in range(2):
    d = max(arr)
    for i in range(n):
        arr[i] = d-arr[i]
    res.append(arr)
print(res)

Output:

[[6, 0, 5, 3, 1], [6, 0, 5, 3, 1]]

Expected Output:

[[0, 6, 1, 3, 5], [6, 0, 5, 3, 1]]

Please help!

Chandresh
  • 140
  • 7
  • 1
    There is only one array named `arr` in this program, which has its contents modified over time, and is appended to `res` twice. If you look at `res` afterwards, then both references to `arr` necessarily show the same contents, because there is only one list to show the contents of. Perhaps you should append a *copy* of `arr` instead, to capture its contents at that moment in time - `res.append(arr[:])` is one way of writing that. – jasonharper Aug 16 '20 at 15:34
  • Maybe also don't use `i` for both your inner and outer for-loop. It's unclear what you intend for it to do. – khelwood Aug 16 '20 at 15:36
  • 1
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – superb rain Aug 16 '20 at 15:49

2 Answers2

2

You put arr in the list res but keep modifying its values in the second loop. Make a new sub-list with values directly, otherwise your changes are reflected on all elements of res which are all identically pointing to arr.

# Using your conventions. 
arr = [5, -1, 4, 2, 0]
res = []
for _ in range(2):
    d = max(arr)
    res.append([])
    for i in range(len(arr)):
        arr[i] = d-arr[i]
        res[-1].append(arr[i])
print(res)

# >>> [[0, 6, 1, 3, 5], [6, 0, 5, 3, 1]]

Note that your variables names are hard to understand so here is a variant:

array = [5, -1, 4, 2, 0]
results = []
for _ in range(2):
    array_max = max(array)
    results.append([])
    for i in range(len(array)):
        array[i] = array_max - array[i]
        results[-1].append(array[i])
print(results)
Guimoute
  • 4,407
  • 3
  • 12
  • 28
2

I would like to use a small function

arr = [5, -1, 4, 2, 0]

def fn(arr):
    s = max(arr)
    return [s - i for i in arr] 

my_final_list = []
for i in range(2):
    arr = fn(arr)
    my_final_list.append(arr)
print(my_final_list)

[[0, 6, 1, 3, 5], [6, 0, 5, 3, 1]]
Vishesh Mangla
  • 664
  • 9
  • 20