[Tutor] Creating a two dimension set

Alan Gauld alan.gauld at yahoo.co.uk
Mon Nov 1 07:54:07 EDT 2021


On 01/11/2021 05:41, Phil wrote:

> Say I have a 9 x 9 array, or a list of lists, and I want to remove a 
> number from grid[0][7]. What simple method would I use? I've tried all 
> sorts of complicated methods but I keep running into problems.

Normally using a 2D table i wouldn't use remove() I'd just
assign a new null value. However...

> However, removing an element from a list of lists is problematic:
> 
> a = [['1','2','3'],['4','5','6']]
> 
> a[0][0] = '9'
> a.remove('9')

a contains 2 lists. So there is no element '9'
You need to access the list that contains the 9:

a[0].remove('9')

But if you know the cell just reassign it directly

a[0][0] = ''

Its also safer since remove removes the first occurrence but if
you have multiple occurrences that might not be what you want.

> Thank you for your detailed description of dictionaries, I'm not sure 
> that a dictionary would be suitable for my case. Can a dictionary 
> contain a set rather than a single number, 

A dict can contain any python object no matter how complex.
Recall that python uses references, it does not store the
actual object in the dict but rather a reference.
So the reference can be to anything.


> grid[0,0] = {1,2,3,4,5,6,7,8,9}
> 
> What about removing a number, won't that fail as in a list of lists?

You call remove on the set not on the dict.

grid[0,0].remove(num)

grid[0,0] returns the set and remove() is then called on the set.

-- 
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