Yes.
If the list of the lists has always 2 element. It's faster to use like > operator than using sorted.
[(i[1], i[0]) if i[0]>i[1] else i for i in lst]
Time:
lst = [(0, 9),
(1, 8),
(2, 7),
(3, 6),
(4, 5),
(5, 4),
(6, 3),
(7, 2),
(8, 1),
(9, 0)]
%timeit [(i[1], i[0]) if i[0]>i[1] else i for i in lst]
1000000 loops, best of 3: 1.96 us per loop
%timeit [sorted(i) for i in lst]
100000 loops, best of 3: 5.87 us per loop
In your case, you said your list has 2 or 3 elements. So your sort function look like this.
def sort_few(lst):
if len(lst)==2:
if lst[0] > lst[1]:
return (lst[1], lst[0])
else:
return lst
else:
if lst[0] > lst[1]:
if lst[1] > lst[2]:
return (lst[2], lst[1], lst[0])
else:
return (lst[1], lst[2], lst[0])
elif lst[1] > lst[2]:
if lst[2] > lst[0]:
return (lst[0], lst[2], lst[1])
else:
return (lst[2], lst[0], lst[1])
elif lst[2] > lst[0]:
if lst[0] > lst[1]:
return (lst[1], lst[0], lst[2])
else:
return lst
Time:
lst = [(1, 2, 3),
(1, 3, 2),
(2, 1, 3),
(2, 3, 1),
(3, 1, 2),
(3, 2, 1),
(1, 2, 3),
(1, 3, 2),
(2, 1, 3),
(2, 3, 1),
(3, 1, 2),
(3, 2, 1)]
%timeit [sort_few(i) for i in lst]
100000 loops, best of 3: 6.3 us per loop
%timeit [sorted(i) for i in lst]
100000 loops, best of 3: 7.32 us per loop
So it's faster to use sort_few than sorted if there are a 2 or 3 element in the list.