# [Tutor] Two dimensional lists

Mark Lawrence breamoreboy at gmail.com
Mon Nov 2 01:58:03 EST 2020

```On 02/11/2020 06:25, Phil wrote:
> On 2/11/20 2:46 pm, Cameron Simpson wrote:
>
>
> For the syntax you show above, the direct Python equivalent is a 5
>> element list, each element of which is a 5 element list.
>>
>> So:
>>
>>      b = [
>>            [ 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 ],
>>          ]
>>
>> The syntax you use "b[3][2]" fetches element 3 (the fourth element,
>> since lists count from 0), and then fetches element 2 from _that_. So
>> the third element of the fourth list.
>
> That's what I expected as well, however, this is the result;
>
>  >>>
>  >>> b = [5],[5]
>  >>> b[3][2] = 9
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> IndexError: tuple index out of range
>  >>> print(b[3][2])
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> IndexError: tuple index out of range

You might like to try things with the interactive interpreter.

>>> b = [5],[5]
>>> type(b)
<class 'tuple'>
>>> b
([5], [5])
>>> b[0]
[5]
>>> b[1]
[5]
>>> b[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> b[0][1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

So you have a tuple of two lists each of which contains one element. The
fact that a comma creates a tuple catches a lot of people :)

>
> I'd spent the last 3 or 4 hours experimenting with this but have not
> achieved anything useful. I also had a play with the array module and I
> had another look at numpy and have decided that's the way to go.
>
> Still, I'm a little disappointed that this has defeated me.
>

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

```