[Tutor] Selecting first matching element from a list

bob gailer bgailer at gmail.com
Wed Jan 14 17:25:51 CET 2009

Noufal Ibrahim wrote:
> bob gailer wrote:
>> 2) "looks bad" and "is ugly" are emotional responses. What are you 
>> feeling and wanting when you say those things?
> It's hard for me to qualify really but my general idea of list 
> comprehensions is that they transform and filter lists creating other 
> lists.
> For instance, I'd call this
> if key in foo:
>   return foo[key]
> else:
>   return 'unknown'
> 'ugly' when compared to
> return foo.get(key,'unknown')
> I guess I'm looking for the idiomatic way of performing such an 
> operation. My gut feel tells me that the zeroth element of a list 
> comprehension is not the right way to go but I wanted 
> confirmation/rebuttal.

I suggest writing the algorithm in step-by-step pseudocode then asking 
"how can I write this in Python"?

High level goal: Given a list of numbers, return the first that meets a 
condition. If none meet the condition, return 'unknown'.
Step-by-step process in pseudocode:

for each element in list
  see if it meets the condition
  if it does
    stop and return the element
if we have not stopped
  return 'unknown'

How many ways are there in Python to go thru a list (and apply a 
function to each element)? The ones I know are:
list comprehension

I discard while as for takes less code and is easier to understand.
I discard map() as it is the "old way" to do a comprehension.

That leaves for and comprehension.

The advantage of for is that you can stop the process once you find the 
desired element.
The advantage of comprehension is compactness and readability.

You must work with the tools available (or write your own). But the 
heart of anything you write will be the original pseudocode.

Then you must live with any emotional reactions.

Bob Gailer
Chapel Hill NC 

More information about the Tutor mailing list