Comparing sequences with range objects

Dieter Maurer dieter at handshake.de
Thu Apr 7 12:42:26 EDT 2022


Antoon Pardon wrote at 2022-4-7 17:16 +0200:
> ...
>Sorry I wasn't clear. The data contains information about persons. But not
>all records need to be complete. So a person can occur multiple times in
>the list, while the records are all different because they are missing
>different bits.
>
>So all records with the same firstname can be duplicates. But if I have
>a record in which the firstname is missing, it can at that point be
>a duplicate of all other records.

The description is still not clear enough. Especially, it does
not show where `range` objects come into play.


Answering on a more abstract level:
Apparently, you want to sort a list the elements of which can
be other lists or range objects.

List objects are ordered lexicographically, i.e. for lists l1, l2:
l1 <= l2 iff not l1 or (l2 and l1[0] <= l2[0] and l1[1:] <= l2[1:]).
If you want to sort a list containing list elements are compared using
this order.

For your case, you would need to use a `key` parameter for `sort` that
implements this order for `range` objects, too.
(Note that Python provides a function which transforms an order
definition into an appropriate `key` function).
A corresponding `sort` call may expand your range objects completely.

An alternative might be to not expand `range` objects but to put them
all at the start or end of the sorted list.
Of course, this would imply that their expansion does not influence
their order in the list -- which may or may not be acceptable
(depending on your use case).
If it is acceptable, it is likely possible to not put range objects
into the list to be sorted in the first place.


More information about the Python-list mailing list