Path: ...!news.mixmin.net!news2.arglkargh.de!news.in-chemnitz.de!3.eu.feeder.erje.net!feeder.erje.net!fu-berlin.de!uni-berlin.de!not-for-mail From: ram@zedat.fu-berlin.de (Stefan Ram) Newsgroups: comp.lang.python Subject: A technique from a chatbot Date: 2 Apr 2024 17:18:16 GMT Organization: Stefan Ram Lines: 61 Expires: 1 Feb 2025 11:59:58 GMT Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de 3X8pLkTXGcuuqfYVeJjcGwdmUS3IwdxmJ0nLzj3m47zYSC Cancel-Lock: sha1:Rs/VAKciprzdfa2s6TZJdqrAPfM= sha256:rQFdBL7OFGwpFO/rzXwQ4yON5J1lZEKh15pJJJgr03c= X-Copyright: (C) Copyright 2024 Stefan Ram. All rights reserved. Distribution through any means other than regular usenet channels is forbidden. It is forbidden to publish this article in the Web, to change URIs of this article into links, and to transfer the body without this notice, but quotations of parts in other Usenet posts are allowed. X-No-Archive: Yes Archive: no X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some services to mirror the article in the web. But the article may be kept on a Usenet archive server with only NNTP access. X-No-Html: yes Content-Language: en-US Bytes: 3209 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 ) . No jumps anymore, yet the loop is aborted on the first hit (if I guess correctly how its working). And it is this combination of "next", a generator, and "None" that the chatbot showed me when I asked him how to get the first component of a list that matches a condition! PS: Let's verify the earliness of the exit out of the loop: Main.py def list_(): list__ =[ 'delta', 'epsilon', 'zeta', 'eta', 'theta' ] for entry in list__: print( f'Now yielding {entry}.' ) yield entry def first_word_beginning_with_e( list_ ): return next( ( word for word in list_() if word[ 0 ]== 'e' ), None ) print( first_word_beginning_with_e( list_ )) sys.stdout Now yielding delta. Now yielding epsilon. epsilon