How to check if an item exist in a nested list

Will Maier willmaier at ml1.net
Thu Jul 19 17:56:32 EDT 2007


On Thu, Jul 19, 2007 at 02:43:13PM -0700, Arash Arfaee wrote:
> One way is to check the length of each dimension. Does any body
> know a simpler way? is there any way to check if "IndexError: list
> index out of range" happened or going to happen and stop program
> from terminating?

If I understand what you're getting at, you could probably use a
dictionary (indexed by (x, y) tuples), too. If you want to test if
an item is in a list, use 'in':

    >>> dinner = ['spam', 'eggs', 'spam', 'spam']
    >>> 'spam' in dinner
    True

'in' uses the __contains__() method implemented by lists.

-- 

[Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/]



More information about the Python-list mailing list