Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing matrix in Python?

Tags:

python

matrix

I'm using this Code to create a python matrix (5 rows, 2 columns) :

[[0 for x in xrange(2)] for x in xrange(5)]

Can some one explain that part 0 for x in xrange(2) and why it didn't worked when i tried to do it as follows :

[[0 for x in xrange(2)] 0 for x in xrange(5)]
like image 371
A.Elnaggar Avatar asked Aug 14 '26 16:08

A.Elnaggar


1 Answers

You have here a nested list comprehension. The first bit

[0 for x in xrange(2)]

creates a list of length 2, with each entry set to 0. This list is set as value for the second list comprehension. The following would yield the same result:

zeros2 = [0 for x in xrange(2)]
# create 5 copies of zeros2
zeros2x5 = [zeros2[:] for x in xrange(5)] 
like image 67
Ludo Avatar answered Aug 16 '26 09:08

Ludo