[Tutor] Matrix

Brian van den Broek bvande at po-box.mcgill.ca
Mon Dec 20 05:18:10 CET 2004


Rob Kapteyn said unto the world upon 2004-12-19 22:44:
> Hello to the list !
> 
> A list of lists is the most logical construction.
> But -- you don't need to assemble the rows separately --
> this works too:
>  >>> my_matrix_as_lists = [ [4, 6, 8, 1],\
> ...                       [2, 5, 1, 3],\
> ...                      [2, 1, 2, 8] ]
> 
>  >>> print my_matrix_as_lists[1][1]
> 5
> 
> Rob
> 
> On Dec 19, 2004, at 1:31 PM, Brian van den Broek wrote:
> 
>> Bugra Cakir said unto the world upon 2004-12-19 10:33:
>>
>>> hi,
>>> I want to create a matrix in Python. For example 3x4 how can i
>>> create this? thanks
>>
>> Hi,
>>
>> at least two ways using only builtins occur to me:
>>
>> 1) A list of lists:
>>
>> .>>> row1 = [4, 6, 8, 1]
>> .>>> row2 = [2, 5, 1, 3]
>> .>>> row3 = [2, 1, 2, 8]
>> .>>> my_matrix_as_lists = [row1, row2, row3]
>> .>>> print my_matrix_as_lists[1][1]
>> 5

<SNIP matrix in a dictionary example>

>> HTH,
>>
>> Brian vdB

Sure, there's no need to assemble the rows separately. But, if you 
collapse it as you did, there is no need for the line continuations, 
either. Since all the lines are enclosed within brackets, if you want to 
span multiple lines, you can just as well do:

.>>> my_matrix_as_lists = [ [4, 6, 8, 1],
                             [2, 5, 1, 3],
                             [2, 1, 2, 8] ]

Best to all,

Brian vdB


More information about the Tutor mailing list