a question regarding conciseness
jeff at ccvcorp.com
Wed Feb 20 16:10:18 EST 2002
Rajarshi Guha wrote:
> for i in d.keys().sort():
> do something
> I get:
> Traceback (innermost last):
> File "<stdin>", line 1, in ?
> TypeError: loop over non-sequence
sort() sorts lists in place, it does not return a value. (Well, technicially,
it returns None...) This was, IIRC, a deliberate design decision. If
mylist.sort() returned the sorted list, then it would be intuitive to expect
that mylist is unchanged, and the sorted list is a copy. That's not the case,
though. While sort() could have been specified to return a copy, there are
many times when one would want to sort a list in-place (such as to save memory
with a very large list). It's easy to make a copy from an in-place sorted
list, but not easy to avoid the copy in other case.
So, in short, what you need to do is:
keys = d.keys()
for key in keys:
Yes, it's an extra couple lines of code, but it isn't much more typing, and it
makes it a little more clear just what's happening.
More information about the Python-list