How to Initialize a Two-Dimensional Array in Python

How to initialize a two-dimensional array in Python?

A pattern that often came up in Python was

bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)

which helped motivate the introduction of list comprehensions, which convert that snippet to

bar = [SOME_EXPRESSION for item in some_iterable]

which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.

Your code follows this pattern twice

twod_list = []                                       \                      
for i in range (0, 10): \
new = [] \ can be replaced } this too
for j in range (0, 10): } with a list /
new.append(foo) / comprehension /
twod_list.append(new) /

How to define a two-dimensional array?

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this
"list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]

#You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

Initializing a two-dimensional array in Python?

In the first one, you are storing the same reference to list m in k. Change in m will be reflected in all the reference.

Where as in second, you are creating new lists in l. Hence, change in one is independent of another.

Alternatively, simpler way to initialize list is as:

  • Holding same reference to list (similar to your first approach) is as:

    >>> row, columns = 2, 3
    >>> my_list = [[0]*columns]*row
    >>> my_list
    [[0, 0, 0], [0, 0, 0]]
    >>> my_list[0][1] = 1 # changing value
    >>> my_list
    [[0, 1, 0], [0, 1, 0]]
    # ^ ^ Reflected in all
  • Holding different reference to the list (similar to your second approach) is as:

    >>> my_list = [[0]*columns for i in range(row)]
    >>> my_list
    [[0, 0, 0], [0, 0, 0]]
    >>> my_list[0][1] = 1 # changing value
    >>> my_list
    [[0, 1, 0], [0, 0, 0]]
    # ^ only one value is changed

How to initialise a 2D array in Python?

If you really want to use for-loops:

>>> board = []
>>> for i in range(3):
... board.append([])
... for j in range(3):
... board[i].append(0)
...
>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

But Python makes this easier for you:

>>> board = [[0]*3 for _ in range(3)]
>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

How to initialize 2D numpy array

Found out the answer myself:
This code does what I want, and shows that I can put a python array ("a") and have it turn into a numpy array. For my code that draws it to a window, it drew it upside down, which is why I added the last line of code.

# generate grid
a = [ ]
allZeroes = []
allOnes = []

for i in range(0,800):
allZeroes.append(0)
allOnes.append(1)

# append 400 rows of 800 zeroes per row.
for i in range(0, 400):
a.append(allZeroes)

# append 400 rows of 800 ones per row.
for i in range(0,400):
a.append(allOnes)

#So this is a 2D 800 x 800 array of zeros on the top half, ones on the bottom half.
array = numpy.array(a)

# Need to flip the array so my other code that draws
# this array will draw it right-side up
array = numpy.flipud(array)

Efficiently initialize 2D array of size n*m in Python 3?

You can use numpy:

import numpy as np
my_array = np.zeros([height, width])

For example:

>>> np.zeros([3, 5])
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])

Note that if you specifically need integers, you should use the dtype argument

>>> np.zeros([3, 5], dtype=int)
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])

How to initialize a two dimensional array in python

You can do it as:

self.vertices = [[] for _ in range(size)]

Example

size = 5

a = [[] for _ in range(size)]
a[2].append(5)

>>> print a
[[], [], [5], [], []]

Between Python and c++ 2d array initialization. What is this ? and why?

In your C++ code:

vector<vector<int>> matrix(m, vector<int>(n, 0));

you're creating a vector of m vectors each containing n elements initialised to 0. That's like a 2d matrix of m rows x n columns.

The equivalent code in Python is:

arr = [[0 for x in range(n)] for y in range(m)]

which is a list comprehension. This syntax looks back to front for people coming from a C++ background, but the format for list comprehension is:

[ expression for item in list if conditional ]

So in your case for every index in the range 0 to m you create an inner list containing n zeroes, i.e. a m x n matrix.

This code:

arr = [[0 for x in range(m)] for y in range(n)]

is not equivalent to your C++ code. It's producing a list of n lists, each containing m zeroes, i.e. a n x m matrix. Hence the errors you got.



Related Topics



Leave a reply



Submit