1

For Example:

a = [1, 3, 5, 4, 2]    
a = a.sort()
print(a)

Output:

None

a = [1, 3, 5, 4, 2]
a.sort()
print(a)

Output:

[1, 2, 3, 4, 5]

My question is why does a = a.sort() reslt in None rather than [1, 2, 3, 4, 5]? But without a= it gives me [1, 2, 3, 4, 5].

Thank you

Mady Daby
  • 1,271
  • 6
  • 18
Den
  • 11
  • 1
  • 7
    Because [`sort`](https://docs.python.org/3/howto/sorting.html) returns `None`. It modifies the list in-place. – Maroun Apr 23 '21 at 17:11
  • 1
    Try `a = sorted(a)`, this function will return a sorted copy of the original list – fafl Apr 23 '21 at 17:12

1 Answers1

1

Because, a.sort returns None, and you are overwriting a's value with that None. The list will still be sorted, because list.sort does that in place. sorted(list) does the inverse : It copies the list, sorts that copy, and returns it. You then have to assign the list to it.

TheEagle
  • 5,808
  • 3
  • 11
  • 39