[Tutor] Two dimensional lists

Alan Gauld alan.gauld at yahoo.co.uk
Mon Nov 2 05:08:44 EST 2020


On 02/11/2020 09:33, Phil wrote:
>
> Declaring a two dimensional array in C takes one line of code, e.g. int 
> b[5][5].
>
> The equivalent in Python takes 7 lines or one long line:
>
> b = [
>      [0] * 5,
>      [0] * 5,
>      [0] * 5,
>      [0] * 5,
>      [0] * 5,
>      ]
>
> My array is [30] [25] which means many lines of code, something I want 
> to avoid. Creating a numpy array is also one line of code.

The point is that you don;t in general declare arrays in Python. You
build them as needed.

So to build the array above you would more likely writer:


b = [[0]*5 for row in range(5)]

Which creates a list b that contains 5 rows each of which is a list of 5
zeros.

If you need to initialize an X by Y table then you would do it:

xy = [[0]*X for row in range(Y)]

Still one line and flexible enough to cope with any sizes.

And you can extend that technique to as many dimensions as you need.

But its fairly unusual that you need to create ;large lists before
using them. You can usually build them by adding the elements
as required. That sometimes requires a different approach to
accessing the data.

Also lists are often not the best option, you can use dictionaries
(C++ maps) and access them with tuples as keys.

mymap = {}

item = mymap[x,y] = 42

print(mymap[x,y])

There is a;so a get() that can return a default value:

val = mypmap.get((5,5),0)  # return 0 since 5,5 isn't there yet

This is probably closest to your original style example.

-- 

Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list