I have written this code in Python to create a nested list, but why the final list is empty in the second case?
The list is not empty in this case:
Code:
list_of_items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def square(x):
return x*x
def cube(x):
return x*x*x
func_list = [square, cube]
final_2 = []
for i in range(10):
var_list = list(map(lambda x: x(i), func_list))
final_2.append(var_list)
print(final_2)
Output:
[[0, 0], [1, 1], [4, 8], [9, 27], [16, 64], [25, 125], [36, 216], [49, 343], [64, 512], [81, 729]]
Now, when I clear the var_list in each iteration (although it should affect the final_2) then the output is empty!!
Code:
list_of_items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def square(x):
return x*x
def cube(x):
return x*x*x
func_list = [square, cube]
final_2 = []
for i in range(10):
var_list = list(map(lambda x: x(i), func_list))
final_2.append(var_list)
var_list.clear()
print(final_2)
Output:
[[], [], [], [], [], [], [], [], [], []]
If the appended list is acting as a pointer, then why the final list is not changed in the first case as the var_list is changing in each iteration and what does clear() do to the final list that it became empty?