[Tutor] Checking if value exist in a '2D array'

Kent Johnson kent37 at tds.net
Fri Jun 17 12:12:10 CEST 2005


Olli Rajala wrote:
> Hi again,
> 
> I have a '2D array', I mean a list inside a list ([[][],[][],...]) and
> would need to check if the value exists in it. Of course I could do a
> for loop, but that just seem to be a little overkill, so is there any
> other way to do it? I have to check the first cell of every insider
> list.

With Python 2.4:
 >>> l= [ [1], [2,3], [4,5], [6]]
 >>> 2 in (i[0] for i in l)
True
 >>> 3 in (i[0] for i in l)
False

with Python 2.3 use [i[0] for i in l] instead which is a little less efficient.

> 
> Here's a little pseudo code if that helps.
> 
> if list[[x][0]] == 'value': # where x can be anything > 0
>    print 'found'
> 
> So, is there a similar method like list.count('value') that I use for 1D lists?

I would use 'value' in list rather than list.count('value') because it will stop when it finds 'value'; list.count() will always inspect the whole list.

Kent



More information about the Tutor mailing list