list index question

Robin Munn rmunn at pobox.com
Wed Apr 2 11:30:15 EST 2003


Post re-arranged to put replies *after* the questions...


Matt Singer <mrsinger at usa.net> wrote:
> "Anna" <revanna at mn.rr.com> wrote in message news:<pan.2003.04.01.15.42.18.291186 at mn.rr.com>...
>> On Tue, 01 Apr 2003 09:38:54 +0000, Anna wrote:
>> 
>> > 
>> >>>> list1=[(100,0), (10,5), (100,10), (100,0)] print list1
>> 
>> Have I mentioned that I *hate* it when my mailreader does this to a simple
>> copy/paste from IDLE... 
>> 
>> That print statement should, of course, have been on a separate line...
>> 
>> Ugh.
>
> Can I wildcard? I don't know the values in the second column.  I want
> to find the first entry what has a particular value in the first
> column.

The list.index() function won't help you, then: it just does a strict
equality comparison. You'll have to write a simple loop:

    index = -1
    for item in sql_result_list:
        index += 1
        if item[0] == 100:
            print "Found it"
            break
    if index >= len(sql_result_list):
        print "Not found"

I know you said you wanted to avoid looping, but this may not be
possible. Why did you want to avoid looping, anyway?

Another thing you may not have thought of is to loop through your
results once and build a dict that you could use for lookup:

    index_dict = {}
    for item in sql_result_list:
        key = item[0]
        index_dict[key] = item

Now you can use index_dict to do O(1) lookups based on the first item of
each tuple. Note that as written, though, only *one* item with the same
key will be kept. There are other ways around that, but I'm getting a
bit far off your original question.

BTW, I rearranged your post so the questions and answers would come in a
sensible order. Please don't top-post -- it's annoying and leads to
confusion. See http://www.caliburn.nl/topposting.html for reasons why.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list