how to get the ordinal number in list

Roy Smith roy at panix.com
Sun Aug 10 14:14:23 EDT 2014


In article <154cc342-7f85-4d16-b636-a1a953913c98 at googlegroups.com>,
 Rustom Mody <rustompmody at gmail.com> wrote:

> >>> l= [6,2,9,12,1,4]
> >>> sorted(l,reverse=True)[:5]
> [12, 9, 6, 4, 2]
> 
> No need to know how sorted works nor [:5]
> 
> Now you (or Steven) can call it abstract.
> 
> And yet its 
> 1. Actual running code in the interpreter
> 2. Its as close as one can get to a literal translation of your
>    "Find the 5 largest numbers in a list"
> [...]
> All the above are clearer than loops+assignments and can be 
> taught before them

I disagree.  For a beginner, you want to be able to break things down 
into individual steps and examine the result at each point.  If you do:

> >>> l= [6,2,9,12,1,4]
> >>> l2 = sorted(l,reverse=True)
> >>> l2[:5]

you have the advantage that you can stop after creating l2 and print it 
out.  The student can see that it has indeed been sorted.  With the 
chained operations, you have to build a mental image of an anonymous, 
temporary list, and then perform the slicing operation on that.  Sure, 
it's the way you or I would write it in production code, but for a 
beginner, breaking it down into smaller pieces makes it easier to 
understand.



More information about the Python-list mailing list