[Tutor] index swap?

Kent Johnson kent37 at tds.net
Sat Feb 24 17:33:45 CET 2007


Switanek, Nick wrote:
> Kent,
> 
> Thank you for the good suggestions. As you suspected, the data were not
> what I thought they were, which is a comforting thought since that's
> more evidence that I can trust python but can't always trust myself (no
> surprise there). I have multiple years of entries for each observation
> and the order of the columns was interchanged midway through. I didn't
> see this at first because the rows are grouped by year, not by
> observation, so looking at the first twenty rows didn't reveal any
> problem.
> 
> Is there a speed advantage to using nested list comps, or stringing
> together multiple string method calls (e.g. str.rstrip().split('\t')),
> as you advise? Or is the main benefit cleaner code? Is there a limit to
> the number of nestings, apart from the potential for confusion in my
> head?

There is probably a speed advantage to the list comps but for me the big 
advantage is ease of use. It takes a little while to get used to the 
syntax and the idea but I find it much more natural because (to me) it 
clearly expresses an idea. I will think, "I need a list of all the lines 
in the file, split by tabs."  The list comp
[ line.split('\t') for line in open('file.txt') ]
expresses this naturally and concisely without introducing anything 
extra. The explicit for loop introduces a lot of mechanism that doesn't 
really have anything to do with the actual concept, it is just the way 
we are used to implementing the concept. The list comp avoids the 
explicit plumbing.

Nested list comps push the readability a bit, in this case it is pretty 
simple.

You can go to extremes to shoehorn something into a list comp but I 
don't see any point to that other than for fun and showing off and 
perhaps a useful optimization.

All IMO of course.

Kent

PS Please reply on-list


More information about the Tutor mailing list