[Tutor] get as a way to operate on first occurrence of an element in a list?

Clay Shirky clay@shirky.com
Sun Aug 3 15:28:02 EDT 2003


>> for line in f:
>>     if line in seen_dict:
>>         pass
>>     else:
>>         print line,
>>         seen_dict[line] = 1
> 
> IMHO Its better to let the test rewflect what you want
> rather than what you don't want...
> 
> if line not in seen_dict:
>  print line
>  seen_dict[line] = 1

Yes, this was Sean's advice too, and the form I'll adopt, many thanks.

> Is there a way to use get to test for a value, fail if
> it doesn't exist, and *then* assign a value to it?
> 
> NOpe, the whole point of get is that it fetches a value
> from the dictionary if it exists and returns the default
> if it doesn't. So it never fails. Its a get() not a set()...

This is what I find so interesting. Most of learning Python for me has been
simply understanding how its done here -- "here's how slices work" sorts of
things. But every now and again I hit something where I have to change the
way I think, from perlish to pythonic.

In perl, the inner loop I am replacing is:

    print unless $seen{$_}++;

Even setting aside the low-level syntax like $ and ;, there are *5* things
in that line that Python disallows: statement before conditional in in-line
blocks, unless as a synonym for not if, the unnamed $_ variable, post-test
incrementing, and auto-creating a variable by altering its value.

People who love perl love that sort of flexibility and density, and people
who hate perl hate the trickiness and unreadability that goes with it.

I, who have a love/hate relationship with perl, understand both points of
view, but am moving towards the latter, as I start sharing more code with
the outside world. After a period of playing around with python, I think I
may have switched over completely. I haven't written a line of perl in three
months, as I'm finding Python's legibility intoxicating...

-clay





More information about the Tutor mailing list