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 allHolding 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
Django Media_Url and Media_Root
How to Use Stringio in Python3
How to Get User Ip Address in Django
Intuition and Idea Behind Reshaping 4D Array to 2D Array in Numpy
How to Open a File Using the Open with Statement
Calculating a Directory's Size Using Python
How to Get the Path of the Current Executed File in Python
How to Plot One Line in Different Colors
Skip the Headers When Editing a CSV File Using Python
How to Generate Keyboard Events
What Is the Purpose of the -M Switch
Python List VS. Array - When to Use
Importerror: No Module Named 'Encodings'
Creating Dataframe from a Dictionary Where Entries Have Different Lengths
What's the Fastest Way of Checking If a Point Is Inside a Polygon in Python
What Are the 'Levels', 'Keys', and Names Arguments for in Pandas' Concat Function
Pyqt: Connecting a Signal to a Slot to Start a Background Operation