Dim
Dim

Reputation: 25

Python. Filling array in the loop

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.

Upvotes: 0

Views: 1428

Answers (1)

kederrac
kederrac

Reputation: 17322

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([])

Upvotes: 1

Related Questions