A
A
AlmazKayum2018-09-07 12:36:01
Python
AlmazKayum, 2018-09-07 12:36:01

How to sort list of tuples in python?

How to sort a list of tuples by the first element of the tuple?
For example, there is
list1 = [(13, 5, 7), (0, 23, 1), (7, 4, 3)]
It needs to become
list2 = [(0, 23, 1), (7, 4, 3) , (13, 5, 7)]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-09-07
@AlmazKayum

And now the correct one:

from operator import itemgetter

list2 = sorted(list1, key=itemgetter(0))

UPD.
As aRegius rightly noted , in this case it is not necessary to provide a comparator function at all, that is, it
will simply work.
My opinion: it's a bit non-obvious. But it works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question