Python usage notes - iterable stuff

From Helpful
Jump to: navigation, search
Various things have their own pages, see Category:Python. Some of the pages that collect various practical notes include:

Sorting

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

sort() for in-place, sorted() for a sorted copy


key

The key parameter should be a callable that fetches the value to sort on from an object. This allows:

  • normalization, e.g. case-insensitive sort via:
lambda x: x.lower()
  • sorting on multiple aspects of things, when you return a tuple. For example empty strings last too via:
lambda x: (x==, x.lower())


When you're fetching from lists, dicts, or attibutes, consider that operator.attrgetter and operator.itemgetter can go a long way, e.g. allowing:

dictlist.sort(key=itemgetter('artist','title'))


Iteratable-related tools

See also: