| | 302 | |
| | 303 | === Sorting requires type consistency === |
| | 304 | |
| | 305 | When sorting iterables with {{{i.sort()}}} or {{{sorted(i)}}}, all elements must have the same type - otherwise it will raise a {{{TypeError}}} in Python-3. |
| | 306 | |
| | 307 | This is particularly relevant when the iterable can contain {{{None}}}. In such a case, use a key function to deal with None: |
| | 308 | {{{#!python |
| | 309 | l = [4,2,7,None] |
| | 310 | |
| | 311 | # Works in Py2, but raises a TypeError in Py3: |
| | 312 | l.sort() |
| | 313 | |
| | 314 | # Works in both: |
| | 315 | l.sort(key=lambda item: item if item is not None else -float('inf')) |
| | 316 | }}} |