Finally started on python..

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat May 12 13:28:28 EDT 2007


In <slrnf4bt4d.64d.roger at julia.computer-surgery.co.uk>, Roger Gammans
wrote:

> I found myself using this sort of code a bit in one of my recent
> scripts
>      class Something:
> 	def Entries(self):
>            sort=self._data.keys()
> 	   sort.sort()
> 	   for i in sort:
> 	      yield i
> 
> IS this preferable to just returning the sort array from the function
> or not? Which is more runtime efficent.

I see no benefit for a generator here as the whole list mus be build for
sorting anyway.  If you still want return an iterable here it could be
written this way:

class Something(object):
    def iter_entries(self):
        return iter(sorted(self._data.keys()))

Just leave out the `iter()` call to return a sorted list.

If you want to make `Something` objects iterable over the sorted keys,
change the method name to `__iter__()`.  Then you can use `Something`
objects like this:

something = Something()
# Puts some entries into `something`.
for entry in something:
    print entry

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list