A technique from a chatbot
Thomas Passin
list1 at tompassin.net
Thu Apr 4 17:10:34 EDT 2024
On 4/4/2024 3:03 PM, Mark Bourne via Python-list wrote:
> Thomas Passin wrote:
>> On 4/2/2024 1:47 PM, Piergiorgio Sartor via Python-list wrote:
>>> On 02/04/2024 19.18, Stefan Ram wrote:
>>>> Some people can't believe it when I say that chatbots improve
>>>> my programming productivity. So, here's a technique I learned
>>>> from a chatbot!
>>>> It is a structured "break". "Break" still is a kind of jump,
>>>> you know?
>>>> So, what's a function to return the first word beginning with
>>>> an "e" in a given list, like for example
>>>> [ 'delta', 'epsilon', 'zeta', 'eta', 'theta' ]
>>>>
>>>> ? Well it's
>>>> def first_word_beginning_with_e( list_ ):
>>>> for word in list_:
>>>> if word[ 0 ]== 'e': return word
>>>>
>>>> . "return" still can be considered a kind of "goto" statement.
>>>> It can lead to errors:
>>>>
>>>> def first_word_beginning_with_e( list_ ):
>>>> for word in list_:
>>>> if word[ 0 ]== 'e': return word
>>>> something_to_be_done_at_the_end_of_this_function()
>>>> The call sometimes will not be executed here!
>>>> So, "return" is similar to "break" in that regard.
>>>> But in Python we can write:
>>>> def first_word_beginning_with_e( list_ ):
>>>> return next( ( word for word in list_ if word[ 0 ]== 'e' ), None )
>>>
>>> Doesn't look a smart advice.
>>>
>>>> . No jumps anymore, yet the loop is aborted on the first hit
>>
>> It's worse than "not a smart advice". This code constructs an
>> unnecessary tuple, then picks out its first element and returns that.
>
> I don't think there's a tuple being created. If you mean:
> ( word for word in list_ if word[ 0 ]== 'e' )
>
> ...that's not creating a tuple. It's a generator expression, which
> generates the next value each time it's called for. If you only ever
> ask for the first item, it only generates that one.
Yes, I was careless when I wrote that. Still, the tuple machinery has to
be created and that's not necessary here. My point was that you are
asking the Python machinery to do extra work for no benefit in
performance or readability.
> When I first came across them, I did find it a bit odd that generator
> expressions look like the tuple equivalent of list/dictionary
> comprehensions.
>
> FWIW, if you actually wanted a tuple from that expression, you'd need to
> pass the generator to tuple's constructor:
> tuple(word for word in list_ if word[0] == 'e')
> (You don't need to include an extra set of brackets when passing a
> generator a the only argument to a function).
>
More information about the Python-list
mailing list