0

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?

  • You're appending a list-reference, effectively. All the inner lists you append all refer to the same underlying list in memory. Any changes/mutations you apply to this list via ANY of the variables that bind to it will affect all other list-references, since they all refer to the same underlying list. – Paul M. Mar 30 '21 at 16:45

2 Answers2

0

You need to append a copy of var_list, not var_list itself, because you are clearing var_list after appending.

from copy import copy

#########
#your code here
#########

for i in range(10):
    var_list = list(map(lambda x: x(i), func_list))
    final_2.append(copy(var_list))
    var_list.clear()
Shady
  • 146
  • 1
  • 5
0

Just don't clear the list. Why do you want to do that?

for i in range(10):
    var_list = list(map(lambda x: x(i), func_list))
    final_2.append(var_list)

You had it right second time around.

In fact, you don't need to give the list a name at all:

for i in range(10):
    final_2.append(list(map(lambda x: x(i), func_list)))
quamrana
  • 33,740
  • 12
  • 54
  • 68