[Tutor] Tweaking list comprehensions

Liam Clarke cyresse at gmail.com
Mon Feb 14 02:09:46 CET 2005


I am fine tuning list comprehensions (at least my understandng
thereof), and I'm not near a Python interpreter at the moment, so I
was wondering if someone could tell me if I did OK -

def approachA(files):

	isHTML = []
	for filename in files:
		if filename.endswith('.htm') or filename.endswith('.html'):
	return isHTML

def approachB(files):

	isHTML = [filename if filename.endswith('.htm') or\
 		  filename.endswith(.html') for filename in files] 
	return isHTML

I wanted approachB to be the list comprehension verstion of approachA.
Did I get the syntax right? All seems somewhat back to front to me,
although when read the comprehension does sorta make sense in a
twisted way.

Feels almost.. Perlesque in it's perverse compactness. That said,
saving myself from the cascading sequential conditionals/loops of
approach A is good, I feel. When it's 2am in the morning, and I've run
out of coffee, 90% of my bugs have been due to the 'cascades' and one
misplaced tab.


Liam Clarke

'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.

More information about the Tutor mailing list