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)]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With