Sorting a list

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • RC

    Sorting a list

    unsortedList = list(["XYZ","ABC"])

    sortedList = unsortedList.so rt()
    print sortedList


    Why this return None?
    How do I get return as ["ABC", "XYZ"]?
  • Steve Holden

    #2
    Re: Sorting a list

    RC wrote:
    unsortedList = list(["XYZ","ABC"])
    >
    sortedList = unsortedList.so rt()
    print sortedList
    >
    >
    Why this return None?
    How do I get return as ["ABC", "XYZ"]?
    The list's .sort method returns None because it modifies the list
    in-place, so after the call it is sorted. So you can either not assign
    the list and use unsortedList (whose name now belies its sorted
    condition) or you can use

    sprtedList = sorted(unsorted List)

    since the sorted() function returns a sorted copy of its argument.

    regards
    Steve
    --
    Steve Holden +1 571 484 6266 +1 800 494 3119
    Holden Web LLC http://www.holdenweb.com/

    Comment

    • duncan smith

      #3
      Re: Sorting a list

      RC wrote:
      unsortedList = list(["XYZ","ABC"])
      >
      sortedList = unsortedList.so rt()
      print sortedList
      >
      >
      Why this return None?
      Because the sort method sorts the list in place (and returns None).
      How do I get return as ["ABC", "XYZ"]?
      >>unsortedLis t = ["XYZ","ABC"]
      >>unsortedList. sort()
      >>unsortedLis t
      ['ABC', 'XYZ']

      or if you want a distinct sorted list (leaving the original list unchanged)
      >>unsortedLis t = ["XYZ","ABC"]
      >>sortedList = sorted(unsorted List)
      >>unsortedLis t
      ['XYZ', 'ABC']
      >>sortedList
      ['ABC', 'XYZ']
      >>>
      Duncan

      Comment

      Working...