-1

I assigned only one y, but how internally it got assigned with 2 y's?

x=[['', 'a', 'b'], ['', 'c', 'd']]*2
print(x)
x[0][0]='y'
print('\n')
print(x)

output

[['', 'a', 'b'], ['', 'c', 'd'], ['', 'a', 'b'], ['', 'c', 'd']]
[['y', 'a', 'b'], ['', 'c', 'd'], ['y', 'a', 'b'], ['', 'c', 'd']]
Nireekshan
  • 317
  • 1
  • 11
  • 1
    you're making two references to the same part of memory. Check this: https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python – anishtain4 Apr 25 '18 at 03:19
  • Erm, actually this one [2D list has weird behavor when trying to modify a single value](https://stackoverflow.com/questions/2739552/2d-list-has-weird-behavor-when-trying-to-modify-a-single-value) – metatoaster Apr 25 '18 at 03:23

1 Answers1

1

You initialize X to be a list of two lists. You can see this in the output from print(x).

But, these two lists are the same object. When you create a list in the way: [values]*n, it will reference the same object n times to populate your list.

Therefore, x[0] is pointing to both instances of ['y', 'a', 'b'].

Travis Black
  • 705
  • 7
  • 18