1

I am trying to sort part of a list.

My list is

A=[3,2,8,1,0,5,4,6,7,9]

I am able to sort the entire list by A.sort()

A.sort() -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

When I apply sort() on part of the list, it doesn't work as expected. My list remains the same.

A[0:4].sort()-> [3,2,8,1,0,5,4,6,7,9]

I know sorted() will work as expected when I apply on part of a list but I would like to know why sort() does't work on part of the list.

Abin John Thomas
  • 159
  • 2
  • 13

1 Answers1

2

Try:

A=[3,2,8,1,0,5,4,6,7,9]
A[0:4] = sorted(A[0:4])
print(A)

Output:

[1, 2, 3, 8, 0, 5, 4, 6, 7, 9]
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39