bpo-39705 : sorted() tutorial example under looping techniques improved (GH-18999)

This commit is contained in:
Rahul Kumaresan 2020-05-18 07:02:34 +05:30 committed by GitHub
parent 65460565df
commit eefd4e0333
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 0 deletions

View File

@ -613,6 +613,21 @@ direction and then call the :func:`reversed` function. ::
To loop over a sequence in sorted order, use the :func:`sorted` function which
returns a new sorted list while leaving the source unaltered. ::
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for i in sorted(basket):
... print(i)
...
apple
apple
banana
orange
orange
pear
Using :func:`set` on a sequence eliminates duplicate elements. The use of
:func:`sorted` in combination with :func:`set` over a sequence is an idiomatic
way to loop over unique elements of the sequence in sorted order. ::
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)

View File

@ -0,0 +1,2 @@
Tutorial example for sorted() in the Loop Techniques section is given a better explanation.
Also a new example is included to explain sorted()'s basic behavior.