Home > Net >  Python list clear() strange behaviour
Python list clear() strange behaviour

Time:05-19

numbers = [12,23,34]
sum = []
for number in numbers:
    num = []
    for n in str(number):
        num.append(int(n))
    sum.append(num)
print(sum)

If i add num.clear() AFTER sum.append(num), it's appending empty array to sum. Why is it happening? It looks like num isn't appended to sum until num is cleared

I know that clear() is unnecessary here because i'm reinitializating num at the beginning of the loop, but this behaviour is strange for me especially if python interpreter goes line by line

CodePudding user response:

num = [] and num.clear() do two different things.

num.clear() tells the list pointed to by num to empty itself. num = [] reassigns num to point to an entirely new (empty) list.

When you do sum.append(num), you're appending that num list to sum -- num still points to that same list, so when you clear it, you're clearing that same list that is now part of sum.

num was not empty at the time you appended it to sum, but calling clear() subsequently empties it. Everything is happening in order; your confusion stems from the fact that you believed it's not possible for the list inside sum to change after it's been appended. Surprise, lists are mutable! :)

(Incidentally, do not name a variable sum -- it's the name of a very useful builtin function and if you want to use that function later in your program you'll be confused as to why it's a list instead of a function!)

CodePudding user response:

num references a particular mutable object. Even after the object is assigned to the sum (btw, don't use sum as variable name, it is a python builtin), you clear the exact same object.

Here is another example to show you the mutation of the list:

numbers = [12,23,34]
Sum = []
for number in numbers:
    num = []
    for n in str(number):
        num.append(int(n))
    Sum.append(num)
num[0] = 'a'

print(Sum)
# [[1, 2], [2, 3], ['a', 4]]

As you can see, num still points to the last added sublist and we change its first item

  • Related