While we cannot mutate a zip object or its items, we can sort by either member. We use sorted()
in this instance since it returns a new list rather than sorting in place (which it cannot do with a zip object, or a tuple). Hopefully this meets with your question:
a = [4, 6, 1, 7, 2, 3, 8, 9, 5]
b = [17, 19, 12, 13, 16, 18, 11, 14, 15]
Those were sorted to start but then I shuffled them both for better demonstration of how sorted()
works.
print (sorted(zip(a, b), key=lambda x: x[0]))
[(1, 12), (2, 16), (3, 18), (4, 17), (5, 15), (6, 19), (7, 13), (8, 11), (9, 14)]
print (sorted(zip(a, b), key=lambda x: x[1]))
[(8, 11), (1, 12), (7, 13), (9, 14), (5, 15), (2, 16), (4, 17), (3, 18), (6, 19)]
See how each case is ordered after sorting? In the first example the first member is in order, in the second example the second member is in order.
Note that the first example doesn’t need a key argument since sorted()
defaults to the first member.
print (sorted(zip(a, b)))
[(1, 12), (2, 16), (3, 18), (4, 17), (5, 15), (6, 19), (7, 13), (8, 11), (9, 14)]
Note that we can have more than two lists in a zip object.
c = ['h', 'j', 'f', 'i', 'b', 'a', 'c', 'd', 'e', 'g']
print (sorted(zip(c, b, a), key=lambda x: x[2]))
[('f', 12, 1), ('b', 16, 2), ('a', 18, 3), ('h', 17, 4), ('e', 15, 5), ('j', 19, 6), ('i', 13, 7), ('c', 11, 8), ('d', 14, 9)]
print (sorted(zip(c, b, a)))
[('a', 18, 3), ('b', 16, 2), ('c', 11, 8), ('d', 14, 9), ('e', 15, 5), ('f', 12, 1), ('h', 17, 4), ('i', 13, 7), ('j', 19, 6)]