Sort a list of tuples by 2nd item (integer value)?

Sort a list of tuples by 2nd item (integer value)?

Asked on November 9, 2018 in Python.
Add Comment


  • 3 Answer(s)

      Try to use the key keyword with sorted().

    sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])
    

      key ought to be a operate that identifies a way to retrieve the comparable component from your arrangement. In your case, it’s the second component of the tuple, therefore we have a tendency to access [1].

      For optimisation, see jamylak’s response mistreatment itemgetter(1), that is basically a quicker version of lambda x: x[1].

    Answered on November 9, 2018.
    Add Comment

      Try this code:

    >>> from operator import itemgetter
    >>> data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
    >>> sorted(data,key=itemgetter(1))
    [('abc', 121), ('abc', 148), ('abc', 221), ('abc', 231)]
    

      IMO using itemgetter is more readable in this case than the solution by @cheeken. It is
    rather than through the use of lambda.

    >python -m timeit -s "from operator import itemgetter; data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=itemgetter(1))"
    1000000 loops, best of 3: 1.22 usec per loop
    >python -m timeit -s "data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=lambda x: x[1])"
    1000000 loops, best of 3: 1.4 usec per loop
    
    Answered on November 9, 2018.
    Add Comment

    This is how you sort a list of tuples by the 2nd item in descending order.

    sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)
    
    
    Answered on November 9, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.