Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use .sort()
#1
The task I need to complete is the usage of .sort() and .split()


## This is the input but the input many vary Peng Ivan Alan Jodi Macy
data = input("Students: ")
data2 = data.split()
data3 = data2.sort()
print('Class Roll')
print(data3)
The expected result is this:

Students: Peng Ivan Alan Jodi Macy
Class Roll
Alan
Ivan
Jodi
Macy
Peng

How can I achieve this and why am I receiving different errors eg. typeerror and attribute error?

Thanks
Reply
#2
The sort method of list is an inline sort and returns None.
In other words, the sort method is sorting the original list.
You should print data2 after the inline-sort.

To sort something, without modification of the original object, you could use the built-in function sorted().
This function returns a new sorted list.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
(Nov-01-2018, 07:49 AM)DeaD_EyE Wrote: The sort method of list is an inline sort and returns None. In other words, the sort method is sorting the original list. You should print data2 after the inline-sort. To sort something, without modification of the original object, you could use the built-in function sorted(). This function returns a new sorted list.

Could you explain how you would do that? I'm kinda confused
Reply
#4
(Nov-01-2018, 08:32 AM)Mrocks22 Wrote: Could you explain how you would do that? I'm kinda confused

data = input("Students: ")
data2 = data.split()
data2.sort()
print('Class Roll')
print(data2)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Nov-01-2018, 09:09 AM)buran Wrote: Peng Ivan Alan Jodi Macy
Thanks finally understood
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to sort a list without .sort() function letmecode 3 3,451 Dec-28-2020, 11:21 PM
Last Post: perfringo
  [split] Manual Sort without Sort function fulir16 2 3,176 Jun-02-2019, 06:13 AM
Last Post: perfringo
  Manual Sort without Sort function dtweaponx 26 49,009 Jun-01-2019, 06:02 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020