0

I need to create 2d array and fill it in the loop. I know how many rows I need, but I don't know what size each row will be after the loop. In C++ I can use:

vector<vector<int>> my_vec(3);
my_vec[0].push_back(1);
my_vec[0].push_back(2);
my_vec[1].push_back(3);
my_vec[2].push_back(4);

And I will have:
1 2
3
4

But when I try python:

aa = [[] * 0] * 3
aa[0].append(5)
aa

output is: [[5], [5], [5]]

I think it's how python creates array, all cells reference to the same memory spot. Right? That's why if I assign some new value to aa[0] = [1,2], then I can append to aa[0] and it will not affect other rows.

So how I can solve this? Create empty array, then fill it adding elements one by one to the row I need. I can use numpy array. Thank you.

5
  • 3
    That's because aa is a list containing the same list over and over. Commented Feb 22, 2020 at 1:37
  • 3
    aa = [[] for _ in range(3)] Commented Feb 22, 2020 at 1:38
  • 3
    That isn't an array, that is a list Commented Feb 22, 2020 at 1:38
  • Mateen Ulhaq, thank you! Got it now. Commented Feb 22, 2020 at 1:52
  • 1
    Does this answer your question? List of lists changes reflected across sublists unexpectedly Commented Feb 22, 2020 at 2:15

1 Answer 1

0

you are right when you multiply a list of lists with a number you are getting one list and many references to the same list and when you are modifying one element you are modifying all, to solve the issue you can try using list comprehension:

aa = [[] for _ in range(3)]

or a for loop:

aa = []

for _ in range(3):
    aa.append([])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.