Sorting a list

R

RC

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

sortedList = unsortedList.sort()
print sortedList


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

Steve Holden

RC said:
unsortedList = list(["XYZ","ABC"])

sortedList = unsortedList.sort()
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(unsortedList)

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

regards
Steve
 
D

duncan smith

RC said:
unsortedList = list(["XYZ","ABC"])

sortedList = unsortedList.sort()
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"]?
unsortedList = ["XYZ","ABC"]
unsortedList.sort()
unsortedList
['ABC', 'XYZ']

or if you want a distinct sorted list (leaving the original list unchanged)
unsortedList = ["XYZ","ABC"]
sortedList = sorted(unsortedList)
unsortedList ['XYZ', 'ABC']
sortedList ['ABC', 'XYZ']

Duncan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top