Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with Sorting
#2
you need to understand the difference between sorted() function and sort() method, e.g. list.sort() method

sorted() built-in function takes iterable and will return it sorted, i.e. you need to assign what it returns to a variable in order to use it later. it can be the same, e.g.
>>> a = [3, 1, 4, 2]
>>> a = sorted(a)
>>> a
[1, 2, 3, 4]
one possible use is to itreate over sorted iterable, without changing the original one
>>> a = [3, 4, 1, 2]
>>> for item in sorted(a):
...    print(item)
... 
1
2
3
4
>>> a
[3, 4, 1, 2]
while sort() method will sort the iterable in place, e.g.
>>> a = [3, 1, 4, 2]
>>> a.sort()
>>> a
[1, 2, 3, 4]
Reply


Messages In This Thread
Help with Sorting - by rsherry8 - Jan-28-2018, 03:36 PM
RE: Help with Sorting - by buran - Jan-28-2018, 04:10 PM
RE: Help with Sorting - by rsherry8 - Jan-28-2018, 04:44 PM
RE: Help with Sorting - by j.crater - Jan-28-2018, 04:54 PM
RE: Help with Sorting - by buran - Jan-28-2018, 05:14 PM
RE: Help with Sorting - by rsherry8 - Jan-28-2018, 05:38 PM
RE: Help with Sorting - by buran - Jan-28-2018, 07:03 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 3,165 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER

Forum Jump:

User Panel Messages

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