Skip to content

Commit a36b45f

Browse files
Doc: clarify that sorted() returns a new list
1 parent 3e9a5b0 commit a36b45f

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

Doc/howto/sorting.rst

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,27 @@ Sorting Basics
1717
==============
1818

1919
A simple ascending sort is very easy: just call the :func:`sorted` function. It
20-
returns a new sorted list:
20+
returns a new sorted list and does not modify the original.
21+
22+
If you do not store or otherwise use the return value, the sorted result is
23+
lost:
2124

2225
.. doctest::
2326

2427
>>> sorted([5, 2, 3, 1, 4])
2528
[1, 2, 3, 4, 5]
2629

30+
>>> original = [5, 2, 3, 1, 4]
31+
>>> sorted(original) # Returns a new sorted list
32+
[1, 2, 3, 4, 5]
33+
>>> original # Original remains unchanged
34+
[5, 2, 3, 1, 4]
35+
36+
>>> # To keep the sorted result, assign it to a variable
37+
>>> sorted_list = sorted(original)
38+
>>> sorted_list
39+
[1, 2, 3, 4, 5]
40+
2741
You can also use the :meth:`list.sort` method. It modifies the list
2842
in-place (and returns ``None`` to avoid confusion). Usually it's less convenient
2943
than :func:`sorted` - but if you don't need the original list, it's slightly
@@ -32,7 +46,7 @@ more efficient.
3246
.. doctest::
3347

3448
>>> a = [5, 2, 3, 1, 4]
35-
>>> a.sort()
49+
>>> a.sort() # Modifies 'a' in-place, returns None
3650
>>> a
3751
[1, 2, 3, 4, 5]
3852

0 commit comments

Comments
 (0)