-1

Welcome All

I try to make list using python named mylist with 3 element each element contain other list contain 2 element like these

[[None,None]]*3

When try to edit first nested list items in my list by set mylist[0][0] = 1 and mylist[0][1] = 2 Then try to print mylist This is output : [[1, 2], [1, 2], [1, 2]] It edit all list items.

However when create it manually like mylist = [[None, None], [None, None], [None, None]] then try to make my edit edition done correctly.

First Case Code :

mylist = [[None,None]]*3

mylist[0][0] = 1
mylist[0][1] = 2

print(mylist)

First Case Output:

[[1, 2], [1, 2], [1, 2]]

Second Case Code :

mylist = [[None, None], [None, None], [None, None]]

mylist[0][0] = 1
mylist[0][1] = 2

print(mylist)

Second Case Output:

[[1, 2], [None, None], [None, None]]
  • List multiplication does not create copies of the list - it repeats a reference to the same list multiple times – rdas Jan 21 '21 at 08:58

1 Answers1

0

That is because multiplying a list doesn't actually create copies of itself like how a string does. For the effect you are looking for, you can use a module called NumPy, use numpy_r for that.

import numpy as np
mylist = np.array([[None, None]] * 3])
print(mylist)

Output will be:

 [[[None None]
 [None None]
 [None None]]]

Or:

import numpy as np
mylist = np.r_[[[None, None]] * 3]
print(mylist)

Which outputs:

[[None None]
 [None None]
 [None None]]

The second one doesn't have an extra dimension, if you didn't figure that out.

If you don't know much about NumPy then click here, you can check here to install NumPy. And if you want to access for eg. the first item, the you use mylist[0][0] but in NumPy arrays, you use mylist[0, 0]. And @Guimoute has the answer in the comments for doing it using standard python without modules.

Edit: I had written some code wrong, I have corrected it. Don't get more frustrated for the code not working, there was just an error.

Shambhav
  • 813
  • 7
  • 20