2
my_list = ['abc', 'def']

outer_list = []
for element in my_list:
    inner_list = []
    for ch in element:
        inner_list.append(ch)
    outer_list.append(inner_list)
print(outer_list)
# output [['a', 'b', 'c'], ['d', 'e', 'f']]

My question is, why does this work? i.e., why does the, line inner_list = [], not obliterate prior instances of inner_list? I think it has to do with the scope of outer_list being outside of the 'for' block. Perhaps once inner_list takes up residence there it is detached from the variable name? Is that close?

Patrick Dennis
  • 323
  • 1
  • 7
  • 1
    Because variable != object. A variable holds a reference. If the reference changes, doesn't necessarily mean the object is destroyed. – cs95 May 30 '18 at 20:18
  • [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). – wim May 30 '18 at 20:21

2 Answers2

1

When you run inner_list=[] it just makes the variable point to another address in the memory. outer_list still points to the old memory address (previous inner_list). While there is a pointer to it, it will not be freed.

Alexandru Antochi
  • 1,295
  • 3
  • 18
  • 42
1

I propose you to consider these 2 cases with full explanation in comments:

  1. Case with list = []:

    my1stList = [1, 2 ,3, 4, 5]  # my1stList references  the list [1, 2 ,3, 4, 5]
    my2ndList = my1stList        # my2ndList references the same list as my1stList
    my1stList = []               # my1stList references another list (which is empty)
    print(my2ndList)             # it prints: [1, 2, 3, 4, 5]
    
  2. Case with list[:] = []:

    my1stList = [1, 2 ,3, 4, 5]  # my1stList references the list [1, 2 ,3, 4, 5]
    my2ndList = my1stList        # my2ndList references the same list as my1stList
    my1stList[:] = []            # the list referenced by my1stList is emptied
    print(my2ndList)             # it prints: []
    

I hope it is now understood for you: each list you append into outer_list is never overwritten. Only its previous reference inner_list changes.

Laurent H.
  • 6,316
  • 1
  • 18
  • 40