EXTREME NOOB, lists?

Steve Holden sholden at holdenweb.com
Fri Sep 1 07:34:21 EDT 2000


skeetor wrote:
> 
> I am trying to compare an input number with several numbers in a list, and
> then to print the range of that number. for example:  I have it ask for a
> number, and i reply with 4.  I want it to check to see if 4 is in the list
> and if so print the range.   I have solved the problem by writing out the
> argument for each number in the list... but it is very long.   I hope i have
> explained this accurately.  and please i am still a retarded four year
> old... so talk slowely and use small words.  thanks.

The index() method of a list will do this for you, but you need to be aware
that it will throw an exception if the item isn't found in the list, so
you must use try: except: to trap that case.

>>> l = [4,5,2,3,11]
>>> l.index(11)
4
>>> l.index(42)
Traceback (innermost last):
  File "<pyshell#55>", line 1, in ?
    l.index(42)
ValueError: list.index(x): x not in list
>>> try:
	pos = l.index(42)
except ValueError:
	print "Could not find 42"

	
Could not find 42

Just another example of how wonderful Python is!

regards
 Steve
-- 
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/



More information about the Python-list mailing list