1

I was just trying to shorten a code snippet in python and came across the strange way of working of the following code.

sample = [[]] * 3

# OUTPUT - [[], [], []] - Simple enough to understand

sample[0].append(1)

# OUTPUT - [[1],[1],[1]] - Why is this happening?

sample[1].append(2) 

# OUTPUT - [[1,2],[1,2],[1,2]] - Why is this happening?

sample[2].append(3) 

# OUTPUT - [[1,2,3],[1,2,3],[1,2,3]] - Why is this happening?

Why is appending to a nested list appending to all the nested lists in the list?

Are all the nested lists pointing to one list? If so where is the original copy of the list?

bigbounty
  • 14,834
  • 4
  • 27
  • 58

1 Answers1

0

Yes, all the nested lists are pointing to one list.

If so where is the original copy of the list?

Not sure what you're asking. Each nested list points to the original list.

jdigital
  • 11,656
  • 4
  • 31
  • 50