1

I wonder why the following Python code

aa = []
for x in range(5):
    bb = aa
    print(bb)
    bb.extend(['a','bb'])
    print(bb)

results in this:

[]
['a', 'bb']
['a', 'bb']
['a', 'bb', 'a', 'bb']
['a', 'bb', 'a', 'bb']
['a', 'bb', 'a', 'bb', 'a', 'bb']
['a', 'bb', 'a', 'bb', 'a', 'bb']
['a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb']
['a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb']
['a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb', 'a', 'bb']

Doesn't the third line bb = aa reset bb to the value of aa which is []? Why is aa also extended when extend was only applied to bb?

Does this mean that bb = aa is not creating a copy of aa in bb but instead only referencing aa? How should I create a copy of aa that is not a reference to aa?

qzx
  • 177
  • 3
  • 10

0 Answers0