[[+content_image]]
R
R
Rapt2014-04-27 19:49:11
Python
Rapt, 2014-04-27 19:49:11

Python creating and populating a 2D array

I'm new to python and it's not clear that when creating an array in this way:
b = [[0] * 2] * 2
And filling:

for i in range(w):
    for r in range(l):
        print(i,r)
        b[i][r] = str(i) + str(r)

The array is not filled with 00; 01; ten; 11, a 10; eleven; ten; 11.
Why so?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
N
nivs, 2014-04-27
@Rapt

Example without numpy, no external libraries at all

#!/usr/bin/env python3
a = 3
b = 5
r = 0  # Чтобы было, чем заполнять
mas = []
for i in range(a):
    mas.append([])
    for j in range(b):
        mas[i].append(r)
        r += 1  # Чтобы заполнялось не одно и тоже

print(mas)
# [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]

D
Damir Makhmutov, 2014-04-27
@doodoo

I will supplement @Bce_OK with an example:

>>> a = [[0] * 2] * 2
>>> a
[[0, 0], [0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0], [1, 0]]
>>>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question