0

Let me first describe the question on which I am working. Its a question from hackerrank - List Comprehensions.

Well here's my solution to that question :

final_list = [];
temp_list = [];

x = int(input());
y = int(input());
z = int(input());
n = int(input());

for i in range(x+1):
    for j in range(y+1):
        for k in range(z+1):
            if((i + j + k) != n):
                temp_list.clear();
                temp_list.append(i);
                temp_list.append(j);
                temp_list.append(k);
                final_list.append(temp_list);

print(final_list);

I used these values as my input : x = 1, y = 1 , z = 1 and n = 2.

Using these values I got output : [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

I am not getting that even I cleared the temp_list then why am I getting this output instead of : [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]].

and moreover, when I declared the temp_list in the if condition itself instead of declaring on the top of the code, I got the answer. can anyone let me know why is this happening ?

Jamzy
  • 31
  • 6
  • [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Lafexlos Jul 03 '17 at 05:59
  • So you mean to say that temp_list got the last value as [1,1,1] and as it is referred by final_list it, the final_list also got changed ! – Jamzy Jul 03 '17 at 06:07
  • Exactly. You can see they are all same by printing `id`. `for item in final_list: print(id(item))` – Lafexlos Jul 03 '17 at 06:43
  • Well,yes thats true. Thank you very much. – Jamzy Jul 03 '17 at 08:27

0 Answers0