Newbie: searching a list

skip at pobox.com skip at pobox.com
Wed May 23 13:28:56 EDT 2001


    Stephen> I have a list generated from a
    Stephen> "sentence=split(some_file.readline())" statement.

    Stephen> A sample list resulting from this statement is:
    Stephen>     ['Independent', 'Variable', '=', '11', ';']

    Stephen> I want to extract the '11', which is the next item in the list
    Stephen> following the equals sign

How about

    try:
        i = sentence.index('=')
	iv = sentence[i+1]
    except (ValueError,IndexError):
        iv = None
    if iv is not None:
        dofunstuffwith(iv)

?  The ValueError catches the case where there is no '=' in the list
(sentence.index fails).  The IndexError catches the case where the statement
is malformed and ends with '='.

-- 
Skip Montanaro (skip at pobox.com)
(847)971-7098




More information about the Python-list mailing list