How to define a two-dimensional array in Python
up vote
563
down vote
favorite
I want to define a two-dimensional array without an initialized length like this:
Matrix =
but it does not work...
I've tried the code below, but it is wrong too:
Matrix = [5][5]
Error:
Traceback ...
IndexError: list index out of range
What is my mistake?
python matrix syntax-error
add a comment |
up vote
563
down vote
favorite
I want to define a two-dimensional array without an initialized length like this:
Matrix =
but it does not work...
I've tried the code below, but it is wrong too:
Matrix = [5][5]
Error:
Traceback ...
IndexError: list index out of range
What is my mistake?
python matrix syntax-error
9
One does not define arrays, or any other thing. You can, however, create multidimensional sequences, as the answers here show. Remember that python variables are untyped, but values are strongly typed.
– SingleNegationElimination
Jul 12 '11 at 16:05
22
IMHO, The question is valid. It involves specific code that doesn't work; the answers told me what I needed to know, about an important, concrete, programming topic. Notice the # of upvotes, and even favorite marks. F.J's answer even showed a way that initialization can be done wrong, and why it is wrong. All very useful.
– ToolmakerSteve
Dec 7 '13 at 19:33
I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in python. Should be said here...
– Dirk Reichel
Jun 5 at 19:48
add a comment |
up vote
563
down vote
favorite
up vote
563
down vote
favorite
I want to define a two-dimensional array without an initialized length like this:
Matrix =
but it does not work...
I've tried the code below, but it is wrong too:
Matrix = [5][5]
Error:
Traceback ...
IndexError: list index out of range
What is my mistake?
python matrix syntax-error
I want to define a two-dimensional array without an initialized length like this:
Matrix =
but it does not work...
I've tried the code below, but it is wrong too:
Matrix = [5][5]
Error:
Traceback ...
IndexError: list index out of range
What is my mistake?
python matrix syntax-error
python matrix syntax-error
edited Nov 12 '17 at 13:09
Peter Mortensen
13.4k1983111
13.4k1983111
asked Jul 12 '11 at 15:54
Masoud Abasian
3,29651820
3,29651820
9
One does not define arrays, or any other thing. You can, however, create multidimensional sequences, as the answers here show. Remember that python variables are untyped, but values are strongly typed.
– SingleNegationElimination
Jul 12 '11 at 16:05
22
IMHO, The question is valid. It involves specific code that doesn't work; the answers told me what I needed to know, about an important, concrete, programming topic. Notice the # of upvotes, and even favorite marks. F.J's answer even showed a way that initialization can be done wrong, and why it is wrong. All very useful.
– ToolmakerSteve
Dec 7 '13 at 19:33
I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in python. Should be said here...
– Dirk Reichel
Jun 5 at 19:48
add a comment |
9
One does not define arrays, or any other thing. You can, however, create multidimensional sequences, as the answers here show. Remember that python variables are untyped, but values are strongly typed.
– SingleNegationElimination
Jul 12 '11 at 16:05
22
IMHO, The question is valid. It involves specific code that doesn't work; the answers told me what I needed to know, about an important, concrete, programming topic. Notice the # of upvotes, and even favorite marks. F.J's answer even showed a way that initialization can be done wrong, and why it is wrong. All very useful.
– ToolmakerSteve
Dec 7 '13 at 19:33
I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in python. Should be said here...
– Dirk Reichel
Jun 5 at 19:48
9
9
One does not define arrays, or any other thing. You can, however, create multidimensional sequences, as the answers here show. Remember that python variables are untyped, but values are strongly typed.
– SingleNegationElimination
Jul 12 '11 at 16:05
One does not define arrays, or any other thing. You can, however, create multidimensional sequences, as the answers here show. Remember that python variables are untyped, but values are strongly typed.
– SingleNegationElimination
Jul 12 '11 at 16:05
22
22
IMHO, The question is valid. It involves specific code that doesn't work; the answers told me what I needed to know, about an important, concrete, programming topic. Notice the # of upvotes, and even favorite marks. F.J's answer even showed a way that initialization can be done wrong, and why it is wrong. All very useful.
– ToolmakerSteve
Dec 7 '13 at 19:33
IMHO, The question is valid. It involves specific code that doesn't work; the answers told me what I needed to know, about an important, concrete, programming topic. Notice the # of upvotes, and even favorite marks. F.J's answer even showed a way that initialization can be done wrong, and why it is wrong. All very useful.
– ToolmakerSteve
Dec 7 '13 at 19:33
I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in python. Should be said here...
– Dirk Reichel
Jun 5 at 19:48
I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in python. Should be said here...
– Dirk Reichel
Jun 5 at 19:48
add a comment |
23 Answers
23
active
oldest
votes
up vote
796
down vote
accepted
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
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.
171
[[0 for x in range(cols_count)] for x in range(rows_count)]
– songhir
Nov 27 '14 at 2:48
3
Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects.
– Dave
Nov 25 '15 at 7:29
3
@dave If you dont need it zero-filled, can userangeto create the internal lists directly:[range(5) for x in range(5)]
– alanjds
Dec 9 '15 at 22:08
2
@alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction.
– Dave
Dec 10 '15 at 16:00
3
@6packkid the[0] * wpart is nice, but[[0] * w] * h]will produce unexpected behavior. Trymat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]])andmat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]]).
– senderle
Jul 19 '17 at 15:45
|
show 6 more comments
up vote
338
down vote
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!
>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.matrix('1 2; 3 4') # use Matlab-style syntax
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy.ndarray((5, 5)) # use the low-level constructor
63
Whenever you want matrices, you want to use numpy. This answer should be first.
– Pat B
Jul 12 '11 at 16:14
1
For numerical matrices, numpy is king. I've had uses of two-dimensional arrays of generators, which I opted for the nested comprehension syntax.
– Prashant Kumar
Jul 12 '11 at 19:41
There's no need for reshape; you can callnumpy.zeroes((5,5,...))to create a multi-dimensional array.
– user1071136
Dec 8 '13 at 20:03
4
I agree that numpy is the way to go for matrices in Python. But sometimes (for example a homework assignment) you just can't use it :(
– dana
Jan 10 '15 at 16:59
1
The fact that the question uses the English word "matrix" doesn't mean that they should usenp.matrixto represent it. The proper way to represent a matrix in numpy is with anarray.
– user2357112
Nov 5 '17 at 20:39
|
show 2 more comments
up vote
275
down vote
Here is a shorter notation for initializing a list of lists:
matrix = [[0]*5 for i in range(5)]
Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
100
great comment about the shortening danger.
– nbubis
Jun 21 '13 at 22:46
13
Thanks for the shortening warning. I was doing that error.
– Gaston Sanchez
Nov 12 '13 at 23:33
2
Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of[0]*5?
– mike622867
Mar 22 '15 at 23:00
1
I spent 30 minutes trying to figure this out before I realized my mistake
– Parth Bhoiwala
Aug 25 '17 at 19:05
7
The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.)
– dreua
Jan 26 at 10:49
|
show 1 more comment
up vote
82
down vote
If you want to create an empty matrix, the correct syntax is
matrix = []
And if you want to generate a matrix of size 5 filled with 0,
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
1
I can not see what it is notor[]but rather[]..
– Koray Tugay
Jun 8 at 1:41
@KorayTugay Because the matrix is represented using Python list(s) (the rows) nested inside another list (the columns).
– elig
Jul 2 at 13:06
For Python-3 use range function instead xrange func
– Rakesh Chaudhari
Aug 28 at 4:25
add a comment |
up vote
66
down vote
If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:
Matrix = {}
Then you can do:
Matrix[1,2] = 15
print Matrix[1,2]
This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.
As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.
Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.
1
Then you can also doimport collections; Matrix = collections.defaultdict(float), to substitute zeros for uninitialized elements.
– osa
Oct 22 '15 at 16:17
2
Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice.
– Vatsal
Nov 16 '15 at 12:25
@Vatsal wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time.
– enobayram
Nov 16 '15 at 13:38
Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity.
– Vatsal
Nov 16 '15 at 14:28
@enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments
– Vatsal
Nov 17 '15 at 4:10
|
show 2 more comments
up vote
36
down vote
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:
matrix =
matrix.append()
matrix.append()
matrix[0].append(2)
matrix[1].append(3)
Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
5
extendwould also be helpful in the first case: If you start withm = [], then you could add to the inner list (extend a row) withm[0].extend([1,2]), and add to the outer list (append a new row) withm.append([3,4]), those operations would leave you with[[1, 2], [3, 4]].
– askewchan
Oct 9 '13 at 16:59
add a comment |
up vote
18
down vote
The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.
l = [ for _ in range(3)]
results in
[, , ]
add a comment |
up vote
17
down vote
You should make a list of lists, and the best way is to use nested comprehensions:
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]'
– Aniruddha Kalburgi
Sep 30 at 1:45
add a comment |
up vote
10
down vote
To declare a matrix of zeros (ones):
numpy.zeros((x, y))
e.g.
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
or
numpy.ones((x, y))
e.g.
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
Even three dimensions are possible.
(http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)
add a comment |
up vote
9
down vote
A rewrite for easy reading:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
add a comment |
up vote
9
down vote
I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
so that
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
add a comment |
up vote
9
down vote
Use:
matrix = [[0]*5 for i in range(5)]
The *5 for the first dimension works because at this level the data is immutable.
add a comment |
up vote
7
down vote
Using NumPy you can initialize empty matrix like this:
import numpy as np
mm = np.matrix()
And later append data like this:
mm = np.append(mm, [[1,2]], axis=1)
whatwould be the pros and cons of using numpy rather than "list comprehension" ?
– ThePassenger
Mar 19 at 22:11
add a comment |
up vote
6
down vote
I read in comma separated files like this:
data=
for l in infile:
l = split(',')
data.append(l)
The list "data" is then a list of lists with index data[row][col]
add a comment |
up vote
6
down vote
rows = int(input())
cols = int(input())
matrix =
for i in range(rows):
row =
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
Why such a long code, that too in Python you ask?
Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)
Anyways, here's the code for a beginner whose coming from C, CPP and Java background
Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.
add a comment |
up vote
4
down vote
Use:
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.
I like this attempt at doing something simple with vanilla Python without having to use numpy.
– Rick Henderson
Jun 7 '16 at 1:01
add a comment |
up vote
4
down vote
If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.
arenumpy.matrixequivalent tonumpy.zeroswithout zeros without being list?
– ThePassenger
Mar 19 at 22:14
add a comment |
up vote
3
down vote
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
Be careful about this short expression, see full explanation down in @F.J's answer
15
Be careful in this way, becauseMatrix[0], Matrix[1], ..., Matrix[4]all point to the same array, so afterMatrix[0][0] = 3, you would expectMatrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3.
– gongzhitaao
Apr 3 '14 at 19:38
Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do.
– Adrian
Nov 20 '14 at 2:18
4
You should remove this answer, since it's not correct answer. Beginners might be confused.
– cxxl
Nov 25 '16 at 20:58
What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers).
– Peter Mortensen
Nov 12 '17 at 13:18
add a comment |
up vote
3
down vote
That's what dictionary is made for!
matrix = {}
You can define keys and values in two ways:
matrix[0,0] = value
or
matrix = { (0,0) : value }
Result:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
add a comment |
up vote
3
down vote
This is how I usually create 2D arrays in python.
col = 3
row = 4
array = [[0] * col for _ in range(row)]
I find this syntax easy to remember compared to using to for loops in a list comprehension.
add a comment |
up vote
2
down vote
If you don't have size information before start then create two one-dimensional lists.
list 1: To store rows
list 2: Actual two-dimensional matrix
Store the entire row in the 1st list. Once done, append list 1 into list 2:
from random import randint
coordinates=
temp=
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
Output:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
add a comment |
up vote
2
down vote
by using list :
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
by using dict:
you can also store this info in the hash table for fast searching like
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
matrix['1'] will give you result in O(1) time
*nb: you need to deal with a collision in the hash table
add a comment |
up vote
0
down vote
l=[[0]*(L) for i in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
add a comment |
protected by Community♦ Dec 6 '16 at 9:11
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
23 Answers
23
active
oldest
votes
23 Answers
23
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
796
down vote
accepted
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
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.
171
[[0 for x in range(cols_count)] for x in range(rows_count)]
– songhir
Nov 27 '14 at 2:48
3
Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects.
– Dave
Nov 25 '15 at 7:29
3
@dave If you dont need it zero-filled, can userangeto create the internal lists directly:[range(5) for x in range(5)]
– alanjds
Dec 9 '15 at 22:08
2
@alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction.
– Dave
Dec 10 '15 at 16:00
3
@6packkid the[0] * wpart is nice, but[[0] * w] * h]will produce unexpected behavior. Trymat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]])andmat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]]).
– senderle
Jul 19 '17 at 15:45
|
show 6 more comments
up vote
796
down vote
accepted
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
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.
171
[[0 for x in range(cols_count)] for x in range(rows_count)]
– songhir
Nov 27 '14 at 2:48
3
Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects.
– Dave
Nov 25 '15 at 7:29
3
@dave If you dont need it zero-filled, can userangeto create the internal lists directly:[range(5) for x in range(5)]
– alanjds
Dec 9 '15 at 22:08
2
@alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction.
– Dave
Dec 10 '15 at 16:00
3
@6packkid the[0] * wpart is nice, but[[0] * w] * h]will produce unexpected behavior. Trymat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]])andmat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]]).
– senderle
Jul 19 '17 at 15:45
|
show 6 more comments
up vote
796
down vote
accepted
up vote
796
down vote
accepted
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
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.
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
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.
edited Feb 6 '17 at 13:44
Hermann Ingjaldsson
4,014143971
4,014143971
answered Jul 12 '11 at 15:59
Manny D
14k12028
14k12028
171
[[0 for x in range(cols_count)] for x in range(rows_count)]
– songhir
Nov 27 '14 at 2:48
3
Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects.
– Dave
Nov 25 '15 at 7:29
3
@dave If you dont need it zero-filled, can userangeto create the internal lists directly:[range(5) for x in range(5)]
– alanjds
Dec 9 '15 at 22:08
2
@alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction.
– Dave
Dec 10 '15 at 16:00
3
@6packkid the[0] * wpart is nice, but[[0] * w] * h]will produce unexpected behavior. Trymat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]])andmat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]]).
– senderle
Jul 19 '17 at 15:45
|
show 6 more comments
171
[[0 for x in range(cols_count)] for x in range(rows_count)]
– songhir
Nov 27 '14 at 2:48
3
Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects.
– Dave
Nov 25 '15 at 7:29
3
@dave If you dont need it zero-filled, can userangeto create the internal lists directly:[range(5) for x in range(5)]
– alanjds
Dec 9 '15 at 22:08
2
@alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction.
– Dave
Dec 10 '15 at 16:00
3
@6packkid the[0] * wpart is nice, but[[0] * w] * h]will produce unexpected behavior. Trymat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]])andmat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]]).
– senderle
Jul 19 '17 at 15:45
171
171
[[0 for x in range(cols_count)] for x in range(rows_count)]
– songhir
Nov 27 '14 at 2:48
[[0 for x in range(cols_count)] for x in range(rows_count)]
– songhir
Nov 27 '14 at 2:48
3
3
Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects.
– Dave
Nov 25 '15 at 7:29
Odd edit by ademar111190. In Python 3 there is no xrange but if you must use Python 2 then xrange is the correct function to use if you don't want to needlessly create objects.
– Dave
Nov 25 '15 at 7:29
3
3
@dave If you dont need it zero-filled, can use
range to create the internal lists directly: [range(5) for x in range(5)]– alanjds
Dec 9 '15 at 22:08
@dave If you dont need it zero-filled, can use
range to create the internal lists directly: [range(5) for x in range(5)]– alanjds
Dec 9 '15 at 22:08
2
2
@alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction.
– Dave
Dec 10 '15 at 16:00
@alanjds - thats true, but you still create potentially many unnecessary object references in Python 2 for the outer iteration (try this with a VERY large range). Also, initialisation to some value is almost always what you want - and this is more often than not 0. range yields an iterable collection - xrange returns a generator. My point was that ademar "corrected" something that was actually more generally correct and efficient than his correction.
– Dave
Dec 10 '15 at 16:00
3
3
@6packkid the
[0] * w part is nice, but [[0] * w] * h] will produce unexpected behavior. Try mat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]]) and mat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]]).– senderle
Jul 19 '17 at 15:45
@6packkid the
[0] * w part is nice, but [[0] * w] * h] will produce unexpected behavior. Try mat = [[0] * 3] * 3; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 10, 0], [0, 10, 0]]) and mat = [[0] * 3 for i in range(3)]; mat[0][1] = 10; print(mat == [[0, 10, 0], [0, 0, 0], [0, 0, 0]]).– senderle
Jul 19 '17 at 15:45
|
show 6 more comments
up vote
338
down vote
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!
>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.matrix('1 2; 3 4') # use Matlab-style syntax
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy.ndarray((5, 5)) # use the low-level constructor
63
Whenever you want matrices, you want to use numpy. This answer should be first.
– Pat B
Jul 12 '11 at 16:14
1
For numerical matrices, numpy is king. I've had uses of two-dimensional arrays of generators, which I opted for the nested comprehension syntax.
– Prashant Kumar
Jul 12 '11 at 19:41
There's no need for reshape; you can callnumpy.zeroes((5,5,...))to create a multi-dimensional array.
– user1071136
Dec 8 '13 at 20:03
4
I agree that numpy is the way to go for matrices in Python. But sometimes (for example a homework assignment) you just can't use it :(
– dana
Jan 10 '15 at 16:59
1
The fact that the question uses the English word "matrix" doesn't mean that they should usenp.matrixto represent it. The proper way to represent a matrix in numpy is with anarray.
– user2357112
Nov 5 '17 at 20:39
|
show 2 more comments
up vote
338
down vote
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!
>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.matrix('1 2; 3 4') # use Matlab-style syntax
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy.ndarray((5, 5)) # use the low-level constructor
63
Whenever you want matrices, you want to use numpy. This answer should be first.
– Pat B
Jul 12 '11 at 16:14
1
For numerical matrices, numpy is king. I've had uses of two-dimensional arrays of generators, which I opted for the nested comprehension syntax.
– Prashant Kumar
Jul 12 '11 at 19:41
There's no need for reshape; you can callnumpy.zeroes((5,5,...))to create a multi-dimensional array.
– user1071136
Dec 8 '13 at 20:03
4
I agree that numpy is the way to go for matrices in Python. But sometimes (for example a homework assignment) you just can't use it :(
– dana
Jan 10 '15 at 16:59
1
The fact that the question uses the English word "matrix" doesn't mean that they should usenp.matrixto represent it. The proper way to represent a matrix in numpy is with anarray.
– user2357112
Nov 5 '17 at 20:39
|
show 2 more comments
up vote
338
down vote
up vote
338
down vote
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!
>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.matrix('1 2; 3 4') # use Matlab-style syntax
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy.ndarray((5, 5)) # use the low-level constructor
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
numpy provides a matrix type as well. It's less commonly used, and some people recommend against using it. But it's useful for people coming to numpy from Matlab, and in some other contexts. I thought I'd include it since we're talking about matrices!
>>> numpy.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.matrix('1 2; 3 4') # use Matlab-style syntax
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy.ndarray((5, 5)) # use the low-level constructor
edited Nov 8 '17 at 0:12
answered Jul 12 '11 at 16:04
senderle
90.6k20164188
90.6k20164188
63
Whenever you want matrices, you want to use numpy. This answer should be first.
– Pat B
Jul 12 '11 at 16:14
1
For numerical matrices, numpy is king. I've had uses of two-dimensional arrays of generators, which I opted for the nested comprehension syntax.
– Prashant Kumar
Jul 12 '11 at 19:41
There's no need for reshape; you can callnumpy.zeroes((5,5,...))to create a multi-dimensional array.
– user1071136
Dec 8 '13 at 20:03
4
I agree that numpy is the way to go for matrices in Python. But sometimes (for example a homework assignment) you just can't use it :(
– dana
Jan 10 '15 at 16:59
1
The fact that the question uses the English word "matrix" doesn't mean that they should usenp.matrixto represent it. The proper way to represent a matrix in numpy is with anarray.
– user2357112
Nov 5 '17 at 20:39
|
show 2 more comments
63
Whenever you want matrices, you want to use numpy. This answer should be first.
– Pat B
Jul 12 '11 at 16:14
1
For numerical matrices, numpy is king. I've had uses of two-dimensional arrays of generators, which I opted for the nested comprehension syntax.
– Prashant Kumar
Jul 12 '11 at 19:41
There's no need for reshape; you can callnumpy.zeroes((5,5,...))to create a multi-dimensional array.
– user1071136
Dec 8 '13 at 20:03
4
I agree that numpy is the way to go for matrices in Python. But sometimes (for example a homework assignment) you just can't use it :(
– dana
Jan 10 '15 at 16:59
1
The fact that the question uses the English word "matrix" doesn't mean that they should usenp.matrixto represent it. The proper way to represent a matrix in numpy is with anarray.
– user2357112
Nov 5 '17 at 20:39
63
63
Whenever you want matrices, you want to use numpy. This answer should be first.
– Pat B
Jul 12 '11 at 16:14
Whenever you want matrices, you want to use numpy. This answer should be first.
– Pat B
Jul 12 '11 at 16:14
1
1
For numerical matrices, numpy is king. I've had uses of two-dimensional arrays of generators, which I opted for the nested comprehension syntax.
– Prashant Kumar
Jul 12 '11 at 19:41
For numerical matrices, numpy is king. I've had uses of two-dimensional arrays of generators, which I opted for the nested comprehension syntax.
– Prashant Kumar
Jul 12 '11 at 19:41
There's no need for reshape; you can call
numpy.zeroes((5,5,...)) to create a multi-dimensional array.– user1071136
Dec 8 '13 at 20:03
There's no need for reshape; you can call
numpy.zeroes((5,5,...)) to create a multi-dimensional array.– user1071136
Dec 8 '13 at 20:03
4
4
I agree that numpy is the way to go for matrices in Python. But sometimes (for example a homework assignment) you just can't use it :(
– dana
Jan 10 '15 at 16:59
I agree that numpy is the way to go for matrices in Python. But sometimes (for example a homework assignment) you just can't use it :(
– dana
Jan 10 '15 at 16:59
1
1
The fact that the question uses the English word "matrix" doesn't mean that they should use
np.matrix to represent it. The proper way to represent a matrix in numpy is with an array.– user2357112
Nov 5 '17 at 20:39
The fact that the question uses the English word "matrix" doesn't mean that they should use
np.matrix to represent it. The proper way to represent a matrix in numpy is with an array.– user2357112
Nov 5 '17 at 20:39
|
show 2 more comments
up vote
275
down vote
Here is a shorter notation for initializing a list of lists:
matrix = [[0]*5 for i in range(5)]
Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
100
great comment about the shortening danger.
– nbubis
Jun 21 '13 at 22:46
13
Thanks for the shortening warning. I was doing that error.
– Gaston Sanchez
Nov 12 '13 at 23:33
2
Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of[0]*5?
– mike622867
Mar 22 '15 at 23:00
1
I spent 30 minutes trying to figure this out before I realized my mistake
– Parth Bhoiwala
Aug 25 '17 at 19:05
7
The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.)
– dreua
Jan 26 at 10:49
|
show 1 more comment
up vote
275
down vote
Here is a shorter notation for initializing a list of lists:
matrix = [[0]*5 for i in range(5)]
Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
100
great comment about the shortening danger.
– nbubis
Jun 21 '13 at 22:46
13
Thanks for the shortening warning. I was doing that error.
– Gaston Sanchez
Nov 12 '13 at 23:33
2
Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of[0]*5?
– mike622867
Mar 22 '15 at 23:00
1
I spent 30 minutes trying to figure this out before I realized my mistake
– Parth Bhoiwala
Aug 25 '17 at 19:05
7
The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.)
– dreua
Jan 26 at 10:49
|
show 1 more comment
up vote
275
down vote
up vote
275
down vote
Here is a shorter notation for initializing a list of lists:
matrix = [[0]*5 for i in range(5)]
Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
Here is a shorter notation for initializing a list of lists:
matrix = [[0]*5 for i in range(5)]
Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
answered Jul 12 '11 at 16:17
Andrew Clark
142k17187250
142k17187250
100
great comment about the shortening danger.
– nbubis
Jun 21 '13 at 22:46
13
Thanks for the shortening warning. I was doing that error.
– Gaston Sanchez
Nov 12 '13 at 23:33
2
Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of[0]*5?
– mike622867
Mar 22 '15 at 23:00
1
I spent 30 minutes trying to figure this out before I realized my mistake
– Parth Bhoiwala
Aug 25 '17 at 19:05
7
The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.)
– dreua
Jan 26 at 10:49
|
show 1 more comment
100
great comment about the shortening danger.
– nbubis
Jun 21 '13 at 22:46
13
Thanks for the shortening warning. I was doing that error.
– Gaston Sanchez
Nov 12 '13 at 23:33
2
Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of[0]*5?
– mike622867
Mar 22 '15 at 23:00
1
I spent 30 minutes trying to figure this out before I realized my mistake
– Parth Bhoiwala
Aug 25 '17 at 19:05
7
The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.)
– dreua
Jan 26 at 10:49
100
100
great comment about the shortening danger.
– nbubis
Jun 21 '13 at 22:46
great comment about the shortening danger.
– nbubis
Jun 21 '13 at 22:46
13
13
Thanks for the shortening warning. I was doing that error.
– Gaston Sanchez
Nov 12 '13 at 23:33
Thanks for the shortening warning. I was doing that error.
– Gaston Sanchez
Nov 12 '13 at 23:33
2
2
Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of
[0]*5?– mike622867
Mar 22 '15 at 23:00
Could you explain the logic behind the "shortening" failure? Why does python output copies of the same list in this case, and an array of different cells in the case of
[0]*5?– mike622867
Mar 22 '15 at 23:00
1
1
I spent 30 minutes trying to figure this out before I realized my mistake
– Parth Bhoiwala
Aug 25 '17 at 19:05
I spent 30 minutes trying to figure this out before I realized my mistake
– Parth Bhoiwala
Aug 25 '17 at 19:05
7
7
The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.)
– dreua
Jan 26 at 10:49
The above comments are not exactly true: [0]*5 still creates a sequence with 5 times a reference to the same Object representing the number 0. But you will never notice this because 0 is immutable (I would say 0 behaves like a value - or you might think of it as a primitive data type - because it is immutable so you never get problems with references to same object instead of having copies.)
– dreua
Jan 26 at 10:49
|
show 1 more comment
up vote
82
down vote
If you want to create an empty matrix, the correct syntax is
matrix = []
And if you want to generate a matrix of size 5 filled with 0,
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
1
I can not see what it is notor[]but rather[]..
– Koray Tugay
Jun 8 at 1:41
@KorayTugay Because the matrix is represented using Python list(s) (the rows) nested inside another list (the columns).
– elig
Jul 2 at 13:06
For Python-3 use range function instead xrange func
– Rakesh Chaudhari
Aug 28 at 4:25
add a comment |
up vote
82
down vote
If you want to create an empty matrix, the correct syntax is
matrix = []
And if you want to generate a matrix of size 5 filled with 0,
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
1
I can not see what it is notor[]but rather[]..
– Koray Tugay
Jun 8 at 1:41
@KorayTugay Because the matrix is represented using Python list(s) (the rows) nested inside another list (the columns).
– elig
Jul 2 at 13:06
For Python-3 use range function instead xrange func
– Rakesh Chaudhari
Aug 28 at 4:25
add a comment |
up vote
82
down vote
up vote
82
down vote
If you want to create an empty matrix, the correct syntax is
matrix = []
And if you want to generate a matrix of size 5 filled with 0,
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
If you want to create an empty matrix, the correct syntax is
matrix = []
And if you want to generate a matrix of size 5 filled with 0,
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
answered Jul 12 '11 at 16:00
mripard
1,360811
1,360811
1
I can not see what it is notor[]but rather[]..
– Koray Tugay
Jun 8 at 1:41
@KorayTugay Because the matrix is represented using Python list(s) (the rows) nested inside another list (the columns).
– elig
Jul 2 at 13:06
For Python-3 use range function instead xrange func
– Rakesh Chaudhari
Aug 28 at 4:25
add a comment |
1
I can not see what it is notor[]but rather[]..
– Koray Tugay
Jun 8 at 1:41
@KorayTugay Because the matrix is represented using Python list(s) (the rows) nested inside another list (the columns).
– elig
Jul 2 at 13:06
For Python-3 use range function instead xrange func
– Rakesh Chaudhari
Aug 28 at 4:25
1
1
I can not see what it is not
or []but rather []..– Koray Tugay
Jun 8 at 1:41
I can not see what it is not
or []but rather []..– Koray Tugay
Jun 8 at 1:41
@KorayTugay Because the matrix is represented using Python list(s) (the rows) nested inside another list (the columns).
– elig
Jul 2 at 13:06
@KorayTugay Because the matrix is represented using Python list(s) (the rows) nested inside another list (the columns).
– elig
Jul 2 at 13:06
For Python-3 use range function instead xrange func
– Rakesh Chaudhari
Aug 28 at 4:25
For Python-3 use range function instead xrange func
– Rakesh Chaudhari
Aug 28 at 4:25
add a comment |
up vote
66
down vote
If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:
Matrix = {}
Then you can do:
Matrix[1,2] = 15
print Matrix[1,2]
This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.
As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.
Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.
1
Then you can also doimport collections; Matrix = collections.defaultdict(float), to substitute zeros for uninitialized elements.
– osa
Oct 22 '15 at 16:17
2
Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice.
– Vatsal
Nov 16 '15 at 12:25
@Vatsal wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time.
– enobayram
Nov 16 '15 at 13:38
Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity.
– Vatsal
Nov 16 '15 at 14:28
@enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments
– Vatsal
Nov 17 '15 at 4:10
|
show 2 more comments
up vote
66
down vote
If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:
Matrix = {}
Then you can do:
Matrix[1,2] = 15
print Matrix[1,2]
This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.
As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.
Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.
1
Then you can also doimport collections; Matrix = collections.defaultdict(float), to substitute zeros for uninitialized elements.
– osa
Oct 22 '15 at 16:17
2
Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice.
– Vatsal
Nov 16 '15 at 12:25
@Vatsal wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time.
– enobayram
Nov 16 '15 at 13:38
Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity.
– Vatsal
Nov 16 '15 at 14:28
@enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments
– Vatsal
Nov 17 '15 at 4:10
|
show 2 more comments
up vote
66
down vote
up vote
66
down vote
If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:
Matrix = {}
Then you can do:
Matrix[1,2] = 15
print Matrix[1,2]
This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.
As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.
Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.
If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:
Matrix = {}
Then you can do:
Matrix[1,2] = 15
print Matrix[1,2]
This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.
As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.
Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.
edited Nov 12 '17 at 13:22
Peter Mortensen
13.4k1983111
13.4k1983111
answered May 29 '14 at 7:23
enobayram
3,7231530
3,7231530
1
Then you can also doimport collections; Matrix = collections.defaultdict(float), to substitute zeros for uninitialized elements.
– osa
Oct 22 '15 at 16:17
2
Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice.
– Vatsal
Nov 16 '15 at 12:25
@Vatsal wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time.
– enobayram
Nov 16 '15 at 13:38
Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity.
– Vatsal
Nov 16 '15 at 14:28
@enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments
– Vatsal
Nov 17 '15 at 4:10
|
show 2 more comments
1
Then you can also doimport collections; Matrix = collections.defaultdict(float), to substitute zeros for uninitialized elements.
– osa
Oct 22 '15 at 16:17
2
Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice.
– Vatsal
Nov 16 '15 at 12:25
@Vatsal wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time.
– enobayram
Nov 16 '15 at 13:38
Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity.
– Vatsal
Nov 16 '15 at 14:28
@enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments
– Vatsal
Nov 17 '15 at 4:10
1
1
Then you can also do
import collections; Matrix = collections.defaultdict(float), to substitute zeros for uninitialized elements.– osa
Oct 22 '15 at 16:17
Then you can also do
import collections; Matrix = collections.defaultdict(float), to substitute zeros for uninitialized elements.– osa
Oct 22 '15 at 16:17
2
2
Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice.
– Vatsal
Nov 16 '15 at 12:25
Wouldn't accessing a dict for tuple(1,2) as key have a worst case complexity of O(n). As internally it would hash the tuples. Whereas using an 2D array would give O(1) time complexity to access index [1,2] access . So using dict for this should not be good choice.
– Vatsal
Nov 16 '15 at 12:25
@Vatsal wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time.
– enobayram
Nov 16 '15 at 13:38
@Vatsal wiki.python.org/moin/TimeComplexity says that the average case is O(1), but you're right about the worst case. Anyway, unless you're talking about A LOT OF ITEMS you wouldn't care about this difference. As a matter of fact, I would be worried more about memory than access time.
– enobayram
Nov 16 '15 at 13:38
Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity.
– Vatsal
Nov 16 '15 at 14:28
Also we always try to avoid use of dicts until the overall complexity of the algorithm is equal or greater than O(n^2). As an 'n' times O(n) accesses would give a O(n^2) complexity.
– Vatsal
Nov 16 '15 at 14:28
@enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments
– Vatsal
Nov 17 '15 at 4:10
@enobayram , Sorry but I do not agree. Asymptotic analysis will always give O(n^2) , if a worst case O(n) access is done 'n' times. Where as Amortized analysis can give a lesser bound. And there is a huge difference between amortized and average case ... please refer before making any assumptions and vague comments
– Vatsal
Nov 17 '15 at 4:10
|
show 2 more comments
up vote
36
down vote
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:
matrix =
matrix.append()
matrix.append()
matrix[0].append(2)
matrix[1].append(3)
Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
5
extendwould also be helpful in the first case: If you start withm = [], then you could add to the inner list (extend a row) withm[0].extend([1,2]), and add to the outer list (append a new row) withm.append([3,4]), those operations would leave you with[[1, 2], [3, 4]].
– askewchan
Oct 9 '13 at 16:59
add a comment |
up vote
36
down vote
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:
matrix =
matrix.append()
matrix.append()
matrix[0].append(2)
matrix[1].append(3)
Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
5
extendwould also be helpful in the first case: If you start withm = [], then you could add to the inner list (extend a row) withm[0].extend([1,2]), and add to the outer list (append a new row) withm.append([3,4]), those operations would leave you with[[1, 2], [3, 4]].
– askewchan
Oct 9 '13 at 16:59
add a comment |
up vote
36
down vote
up vote
36
down vote
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:
matrix =
matrix.append()
matrix.append()
matrix[0].append(2)
matrix[1].append(3)
Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:
matrix =
matrix.append()
matrix.append()
matrix[0].append(2)
matrix[1].append(3)
Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
answered Jul 12 '11 at 16:04
wberry
11.6k43869
11.6k43869
5
extendwould also be helpful in the first case: If you start withm = [], then you could add to the inner list (extend a row) withm[0].extend([1,2]), and add to the outer list (append a new row) withm.append([3,4]), those operations would leave you with[[1, 2], [3, 4]].
– askewchan
Oct 9 '13 at 16:59
add a comment |
5
extendwould also be helpful in the first case: If you start withm = [], then you could add to the inner list (extend a row) withm[0].extend([1,2]), and add to the outer list (append a new row) withm.append([3,4]), those operations would leave you with[[1, 2], [3, 4]].
– askewchan
Oct 9 '13 at 16:59
5
5
extend would also be helpful in the first case: If you start with m = [], then you could add to the inner list (extend a row) with m[0].extend([1,2]), and add to the outer list (append a new row) with m.append([3,4]), those operations would leave you with [[1, 2], [3, 4]].– askewchan
Oct 9 '13 at 16:59
extend would also be helpful in the first case: If you start with m = [], then you could add to the inner list (extend a row) with m[0].extend([1,2]), and add to the outer list (append a new row) with m.append([3,4]), those operations would leave you with [[1, 2], [3, 4]].– askewchan
Oct 9 '13 at 16:59
add a comment |
up vote
18
down vote
The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.
l = [ for _ in range(3)]
results in
[, , ]
add a comment |
up vote
18
down vote
The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.
l = [ for _ in range(3)]
results in
[, , ]
add a comment |
up vote
18
down vote
up vote
18
down vote
The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.
l = [ for _ in range(3)]
results in
[, , ]
The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.
l = [ for _ in range(3)]
results in
[, , ]
edited Dec 4 '15 at 14:31
answered Dec 4 '15 at 14:13
Fabian
1,76632029
1,76632029
add a comment |
add a comment |
up vote
17
down vote
You should make a list of lists, and the best way is to use nested comprehensions:
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]'
– Aniruddha Kalburgi
Sep 30 at 1:45
add a comment |
up vote
17
down vote
You should make a list of lists, and the best way is to use nested comprehensions:
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]'
– Aniruddha Kalburgi
Sep 30 at 1:45
add a comment |
up vote
17
down vote
up vote
17
down vote
You should make a list of lists, and the best way is to use nested comprehensions:
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
You should make a list of lists, and the best way is to use nested comprehensions:
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
edited Nov 12 '17 at 13:11
Peter Mortensen
13.4k1983111
13.4k1983111
answered Jul 12 '11 at 16:00
utdemir
18.3k84475
18.3k84475
Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]'
– Aniruddha Kalburgi
Sep 30 at 1:45
add a comment |
Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]'
– Aniruddha Kalburgi
Sep 30 at 1:45
Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]'
– Aniruddha Kalburgi
Sep 30 at 1:45
Actually the sequence for row_index('i') and column_index('j') are as follows: '>>> matrix = [[0 for column_index in range(5)] for row_index in range(5)]'
– Aniruddha Kalburgi
Sep 30 at 1:45
add a comment |
up vote
10
down vote
To declare a matrix of zeros (ones):
numpy.zeros((x, y))
e.g.
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
or
numpy.ones((x, y))
e.g.
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
Even three dimensions are possible.
(http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)
add a comment |
up vote
10
down vote
To declare a matrix of zeros (ones):
numpy.zeros((x, y))
e.g.
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
or
numpy.ones((x, y))
e.g.
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
Even three dimensions are possible.
(http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)
add a comment |
up vote
10
down vote
up vote
10
down vote
To declare a matrix of zeros (ones):
numpy.zeros((x, y))
e.g.
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
or
numpy.ones((x, y))
e.g.
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
Even three dimensions are possible.
(http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)
To declare a matrix of zeros (ones):
numpy.zeros((x, y))
e.g.
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
or
numpy.ones((x, y))
e.g.
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
Even three dimensions are possible.
(http://www.astro.ufl.edu/~warner/prog/python.html see --> Multi-dimensional arrays)
answered Dec 7 '13 at 20:45
khaz
10616
10616
add a comment |
add a comment |
up vote
9
down vote
A rewrite for easy reading:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
add a comment |
up vote
9
down vote
A rewrite for easy reading:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
add a comment |
up vote
9
down vote
up vote
9
down vote
A rewrite for easy reading:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
A rewrite for easy reading:
# 2D array/ matrix
# 5 rows, 5 cols
rows_count = 5
cols_count = 5
# create
# creation looks reverse
# create an array of "cols_count" cols, for each of the "rows_count" rows
# all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]
# index is from 0 to 4
# for both rows & cols
# since 5 rows, 5 cols
# use
two_d_array[0][0] = 1
print two_d_array[0][0] # prints 1 # 1st row, 1st col (top-left element of matrix)
two_d_array[1][0] = 2
print two_d_array[1][0] # prints 2 # 2nd row, 1st col
two_d_array[1][4] = 3
print two_d_array[1][4] # prints 3 # 2nd row, last col
two_d_array[4][4] = 4
print two_d_array[4][4] # prints 4 # last row, last col (right, bottom element of matrix)
edited Jul 2 '16 at 11:41
answered Jul 2 '16 at 11:33
Manohar Reddy Poreddy
4,4934444
4,4934444
add a comment |
add a comment |
up vote
9
down vote
I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
so that
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
add a comment |
up vote
9
down vote
I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
so that
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
add a comment |
up vote
9
down vote
up vote
9
down vote
I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
so that
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
so that
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
edited Nov 12 '17 at 13:20
Peter Mortensen
13.4k1983111
13.4k1983111
answered Mar 28 '14 at 10:14
user110954
50266
50266
add a comment |
add a comment |
up vote
9
down vote
Use:
matrix = [[0]*5 for i in range(5)]
The *5 for the first dimension works because at this level the data is immutable.
add a comment |
up vote
9
down vote
Use:
matrix = [[0]*5 for i in range(5)]
The *5 for the first dimension works because at this level the data is immutable.
add a comment |
up vote
9
down vote
up vote
9
down vote
Use:
matrix = [[0]*5 for i in range(5)]
The *5 for the first dimension works because at this level the data is immutable.
Use:
matrix = [[0]*5 for i in range(5)]
The *5 for the first dimension works because at this level the data is immutable.
edited Nov 12 '17 at 13:22
Peter Mortensen
13.4k1983111
13.4k1983111
answered Aug 5 '15 at 1:10
innov8
7331016
7331016
add a comment |
add a comment |
up vote
7
down vote
Using NumPy you can initialize empty matrix like this:
import numpy as np
mm = np.matrix()
And later append data like this:
mm = np.append(mm, [[1,2]], axis=1)
whatwould be the pros and cons of using numpy rather than "list comprehension" ?
– ThePassenger
Mar 19 at 22:11
add a comment |
up vote
7
down vote
Using NumPy you can initialize empty matrix like this:
import numpy as np
mm = np.matrix()
And later append data like this:
mm = np.append(mm, [[1,2]], axis=1)
whatwould be the pros and cons of using numpy rather than "list comprehension" ?
– ThePassenger
Mar 19 at 22:11
add a comment |
up vote
7
down vote
up vote
7
down vote
Using NumPy you can initialize empty matrix like this:
import numpy as np
mm = np.matrix()
And later append data like this:
mm = np.append(mm, [[1,2]], axis=1)
Using NumPy you can initialize empty matrix like this:
import numpy as np
mm = np.matrix()
And later append data like this:
mm = np.append(mm, [[1,2]], axis=1)
edited Nov 12 '17 at 13:26
Peter Mortensen
13.4k1983111
13.4k1983111
answered Sep 15 '17 at 10:54
Namrata Tolani
44555
44555
whatwould be the pros and cons of using numpy rather than "list comprehension" ?
– ThePassenger
Mar 19 at 22:11
add a comment |
whatwould be the pros and cons of using numpy rather than "list comprehension" ?
– ThePassenger
Mar 19 at 22:11
whatwould be the pros and cons of using numpy rather than "list comprehension" ?
– ThePassenger
Mar 19 at 22:11
whatwould be the pros and cons of using numpy rather than "list comprehension" ?
– ThePassenger
Mar 19 at 22:11
add a comment |
up vote
6
down vote
I read in comma separated files like this:
data=
for l in infile:
l = split(',')
data.append(l)
The list "data" is then a list of lists with index data[row][col]
add a comment |
up vote
6
down vote
I read in comma separated files like this:
data=
for l in infile:
l = split(',')
data.append(l)
The list "data" is then a list of lists with index data[row][col]
add a comment |
up vote
6
down vote
up vote
6
down vote
I read in comma separated files like this:
data=
for l in infile:
l = split(',')
data.append(l)
The list "data" is then a list of lists with index data[row][col]
I read in comma separated files like this:
data=
for l in infile:
l = split(',')
data.append(l)
The list "data" is then a list of lists with index data[row][col]
answered Sep 4 '13 at 19:40
wsanders
8424
8424
add a comment |
add a comment |
up vote
6
down vote
rows = int(input())
cols = int(input())
matrix =
for i in range(rows):
row =
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
Why such a long code, that too in Python you ask?
Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)
Anyways, here's the code for a beginner whose coming from C, CPP and Java background
Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.
add a comment |
up vote
6
down vote
rows = int(input())
cols = int(input())
matrix =
for i in range(rows):
row =
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
Why such a long code, that too in Python you ask?
Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)
Anyways, here's the code for a beginner whose coming from C, CPP and Java background
Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.
add a comment |
up vote
6
down vote
up vote
6
down vote
rows = int(input())
cols = int(input())
matrix =
for i in range(rows):
row =
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
Why such a long code, that too in Python you ask?
Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)
Anyways, here's the code for a beginner whose coming from C, CPP and Java background
Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.
rows = int(input())
cols = int(input())
matrix =
for i in range(rows):
row =
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
Why such a long code, that too in Python you ask?
Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn't give me any information on what Python was doing. Also note that I am not aware of these shorthands.)
Anyways, here's the code for a beginner whose coming from C, CPP and Java background
Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.
answered Jul 6 at 21:06
vardin
577816
577816
add a comment |
add a comment |
up vote
4
down vote
Use:
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.
I like this attempt at doing something simple with vanilla Python without having to use numpy.
– Rick Henderson
Jun 7 '16 at 1:01
add a comment |
up vote
4
down vote
Use:
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.
I like this attempt at doing something simple with vanilla Python without having to use numpy.
– Rick Henderson
Jun 7 '16 at 1:01
add a comment |
up vote
4
down vote
up vote
4
down vote
Use:
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.
Use:
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.
edited Nov 12 '17 at 13:23
Peter Mortensen
13.4k1983111
13.4k1983111
answered Nov 1 '15 at 7:48
pterodragon
130312
130312
I like this attempt at doing something simple with vanilla Python without having to use numpy.
– Rick Henderson
Jun 7 '16 at 1:01
add a comment |
I like this attempt at doing something simple with vanilla Python without having to use numpy.
– Rick Henderson
Jun 7 '16 at 1:01
I like this attempt at doing something simple with vanilla Python without having to use numpy.
– Rick Henderson
Jun 7 '16 at 1:01
I like this attempt at doing something simple with vanilla Python without having to use numpy.
– Rick Henderson
Jun 7 '16 at 1:01
add a comment |
up vote
4
down vote
If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.
arenumpy.matrixequivalent tonumpy.zeroswithout zeros without being list?
– ThePassenger
Mar 19 at 22:14
add a comment |
up vote
4
down vote
If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.
arenumpy.matrixequivalent tonumpy.zeroswithout zeros without being list?
– ThePassenger
Mar 19 at 22:14
add a comment |
up vote
4
down vote
up vote
4
down vote
If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.
If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.
edited Nov 12 '17 at 13:24
Peter Mortensen
13.4k1983111
13.4k1983111
answered Jul 14 '16 at 8:55
alessadnro
412
412
arenumpy.matrixequivalent tonumpy.zeroswithout zeros without being list?
– ThePassenger
Mar 19 at 22:14
add a comment |
arenumpy.matrixequivalent tonumpy.zeroswithout zeros without being list?
– ThePassenger
Mar 19 at 22:14
are
numpy.matrix equivalent to numpy.zeros without zeros without being list?– ThePassenger
Mar 19 at 22:14
are
numpy.matrix equivalent to numpy.zeros without zeros without being list?– ThePassenger
Mar 19 at 22:14
add a comment |
up vote
3
down vote
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
Be careful about this short expression, see full explanation down in @F.J's answer
15
Be careful in this way, becauseMatrix[0], Matrix[1], ..., Matrix[4]all point to the same array, so afterMatrix[0][0] = 3, you would expectMatrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3.
– gongzhitaao
Apr 3 '14 at 19:38
Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do.
– Adrian
Nov 20 '14 at 2:18
4
You should remove this answer, since it's not correct answer. Beginners might be confused.
– cxxl
Nov 25 '16 at 20:58
What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers).
– Peter Mortensen
Nov 12 '17 at 13:18
add a comment |
up vote
3
down vote
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
Be careful about this short expression, see full explanation down in @F.J's answer
15
Be careful in this way, becauseMatrix[0], Matrix[1], ..., Matrix[4]all point to the same array, so afterMatrix[0][0] = 3, you would expectMatrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3.
– gongzhitaao
Apr 3 '14 at 19:38
Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do.
– Adrian
Nov 20 '14 at 2:18
4
You should remove this answer, since it's not correct answer. Beginners might be confused.
– cxxl
Nov 25 '16 at 20:58
What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers).
– Peter Mortensen
Nov 12 '17 at 13:18
add a comment |
up vote
3
down vote
up vote
3
down vote
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
Be careful about this short expression, see full explanation down in @F.J's answer
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
Be careful about this short expression, see full explanation down in @F.J's answer
edited Apr 3 '14 at 19:58
gongzhitaao
4,64612537
4,64612537
answered Feb 8 '14 at 10:24
和風信使
9512
9512
15
Be careful in this way, becauseMatrix[0], Matrix[1], ..., Matrix[4]all point to the same array, so afterMatrix[0][0] = 3, you would expectMatrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3.
– gongzhitaao
Apr 3 '14 at 19:38
Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do.
– Adrian
Nov 20 '14 at 2:18
4
You should remove this answer, since it's not correct answer. Beginners might be confused.
– cxxl
Nov 25 '16 at 20:58
What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers).
– Peter Mortensen
Nov 12 '17 at 13:18
add a comment |
15
Be careful in this way, becauseMatrix[0], Matrix[1], ..., Matrix[4]all point to the same array, so afterMatrix[0][0] = 3, you would expectMatrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3.
– gongzhitaao
Apr 3 '14 at 19:38
Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do.
– Adrian
Nov 20 '14 at 2:18
4
You should remove this answer, since it's not correct answer. Beginners might be confused.
– cxxl
Nov 25 '16 at 20:58
What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers).
– Peter Mortensen
Nov 12 '17 at 13:18
15
15
Be careful in this way, because
Matrix[0], Matrix[1], ..., Matrix[4] all point to the same array, so after Matrix[0][0] = 3, you would expect Matrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3.– gongzhitaao
Apr 3 '14 at 19:38
Be careful in this way, because
Matrix[0], Matrix[1], ..., Matrix[4] all point to the same array, so after Matrix[0][0] = 3, you would expect Matrix[0][0] == Matrix[1][0] == ... == Matrix[4][0] == 3.– gongzhitaao
Apr 3 '14 at 19:38
Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do.
– Adrian
Nov 20 '14 at 2:18
Thanks gongzhitaao for your comment. Had I read it elier it would have saved me at least half an hour.. Having a matrix where each row points to the same place in memory doesn't seem to be very useful, and if you are not aware of what you are doing it even is dangerous! I am pretty sure this is NOT what Masoud Abasian, who asked the question, wants to do.
– Adrian
Nov 20 '14 at 2:18
4
4
You should remove this answer, since it's not correct answer. Beginners might be confused.
– cxxl
Nov 25 '16 at 20:58
You should remove this answer, since it's not correct answer. Beginners might be confused.
– cxxl
Nov 25 '16 at 20:58
What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers).
– Peter Mortensen
Nov 12 '17 at 13:18
What answer are you referring to? I don't see a user with the name "F.J" (not even in deleted answers).
– Peter Mortensen
Nov 12 '17 at 13:18
add a comment |
up vote
3
down vote
That's what dictionary is made for!
matrix = {}
You can define keys and values in two ways:
matrix[0,0] = value
or
matrix = { (0,0) : value }
Result:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
add a comment |
up vote
3
down vote
That's what dictionary is made for!
matrix = {}
You can define keys and values in two ways:
matrix[0,0] = value
or
matrix = { (0,0) : value }
Result:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
add a comment |
up vote
3
down vote
up vote
3
down vote
That's what dictionary is made for!
matrix = {}
You can define keys and values in two ways:
matrix[0,0] = value
or
matrix = { (0,0) : value }
Result:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
That's what dictionary is made for!
matrix = {}
You can define keys and values in two ways:
matrix[0,0] = value
or
matrix = { (0,0) : value }
Result:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
edited Nov 12 '17 at 13:16
Peter Mortensen
13.4k1983111
13.4k1983111
answered Jan 16 '17 at 6:38
KouchakYazdi
6051016
6051016
add a comment |
add a comment |
up vote
3
down vote
This is how I usually create 2D arrays in python.
col = 3
row = 4
array = [[0] * col for _ in range(row)]
I find this syntax easy to remember compared to using to for loops in a list comprehension.
add a comment |
up vote
3
down vote
This is how I usually create 2D arrays in python.
col = 3
row = 4
array = [[0] * col for _ in range(row)]
I find this syntax easy to remember compared to using to for loops in a list comprehension.
add a comment |
up vote
3
down vote
up vote
3
down vote
This is how I usually create 2D arrays in python.
col = 3
row = 4
array = [[0] * col for _ in range(row)]
I find this syntax easy to remember compared to using to for loops in a list comprehension.
This is how I usually create 2D arrays in python.
col = 3
row = 4
array = [[0] * col for _ in range(row)]
I find this syntax easy to remember compared to using to for loops in a list comprehension.
answered Jun 3 at 15:32
Michael
295314
295314
add a comment |
add a comment |
up vote
2
down vote
If you don't have size information before start then create two one-dimensional lists.
list 1: To store rows
list 2: Actual two-dimensional matrix
Store the entire row in the 1st list. Once done, append list 1 into list 2:
from random import randint
coordinates=
temp=
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
Output:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
add a comment |
up vote
2
down vote
If you don't have size information before start then create two one-dimensional lists.
list 1: To store rows
list 2: Actual two-dimensional matrix
Store the entire row in the 1st list. Once done, append list 1 into list 2:
from random import randint
coordinates=
temp=
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
Output:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
add a comment |
up vote
2
down vote
up vote
2
down vote
If you don't have size information before start then create two one-dimensional lists.
list 1: To store rows
list 2: Actual two-dimensional matrix
Store the entire row in the 1st list. Once done, append list 1 into list 2:
from random import randint
coordinates=
temp=
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
Output:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
If you don't have size information before start then create two one-dimensional lists.
list 1: To store rows
list 2: Actual two-dimensional matrix
Store the entire row in the 1st list. Once done, append list 1 into list 2:
from random import randint
coordinates=
temp=
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
Output:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
edited Nov 12 '17 at 13:26
Peter Mortensen
13.4k1983111
13.4k1983111
answered Aug 5 '17 at 11:55
Nagendra Nigade
552720
552720
add a comment |
add a comment |
up vote
2
down vote
by using list :
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
by using dict:
you can also store this info in the hash table for fast searching like
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
matrix['1'] will give you result in O(1) time
*nb: you need to deal with a collision in the hash table
add a comment |
up vote
2
down vote
by using list :
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
by using dict:
you can also store this info in the hash table for fast searching like
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
matrix['1'] will give you result in O(1) time
*nb: you need to deal with a collision in the hash table
add a comment |
up vote
2
down vote
up vote
2
down vote
by using list :
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
by using dict:
you can also store this info in the hash table for fast searching like
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
matrix['1'] will give you result in O(1) time
*nb: you need to deal with a collision in the hash table
by using list :
matrix_in_python = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]
by using dict:
you can also store this info in the hash table for fast searching like
matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};
matrix['1'] will give you result in O(1) time
*nb: you need to deal with a collision in the hash table
edited Feb 5 at 5:10
answered Feb 5 at 4:27
Saurabh Chandra Patel
5,50714660
5,50714660
add a comment |
add a comment |
up vote
0
down vote
l=[[0]*(L) for i in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
add a comment |
up vote
0
down vote
l=[[0]*(L) for i in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
add a comment |
up vote
0
down vote
up vote
0
down vote
l=[[0]*(L) for i in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
l=[[0]*(L) for i in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
edited Nov 18 at 17:17
Yuval Pruss
2,08431435
2,08431435
answered Nov 18 at 14:02
Harsh Sharma
7,69721018
7,69721018
add a comment |
add a comment |
protected by Community♦ Dec 6 '16 at 9:11
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
9
One does not define arrays, or any other thing. You can, however, create multidimensional sequences, as the answers here show. Remember that python variables are untyped, but values are strongly typed.
– SingleNegationElimination
Jul 12 '11 at 16:05
22
IMHO, The question is valid. It involves specific code that doesn't work; the answers told me what I needed to know, about an important, concrete, programming topic. Notice the # of upvotes, and even favorite marks. F.J's answer even showed a way that initialization can be done wrong, and why it is wrong. All very useful.
– ToolmakerSteve
Dec 7 '13 at 19:33
I'm confused. Coming from other languages: it IS a difference between an 1D-Array containing 1D-Arrays and a 2D-Array. And AFAIK there is no way of having a multi-dimensional-array (or list) in python. Should be said here...
– Dirk Reichel
Jun 5 at 19:48