Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eefd4e0

Browse files
authored
bpo-39705 : sorted() tutorial example under looping techniques improved (GH-18999)
1 parent 6546056 commit eefd4e0

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

Doc/tutorial/datastructures.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -613,6 +613,21 @@ direction and then call the :func:`reversed` function. ::
613613
To loop over a sequence in sorted order, use the :func:`sorted` function which
614614
returns a new sorted list while leaving the source unaltered. ::
615615

616+
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
617+
>>> for i in sorted(basket):
618+
... print(i)
619+
...
620+
apple
621+
apple
622+
banana
623+
orange
624+
orange
625+
pear
626+
627+
Using :func:`set` on a sequence eliminates duplicate elements. The use of
628+
:func:`sorted` in combination with :func:`set` over a sequence is an idiomatic
629+
way to loop over unique elements of the sequence in sorted order. ::
630+
616631
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
617632
>>> for f in sorted(set(basket)):
618633
... print(f)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Tutorial example for sorted() in the Loop Techniques section is given a better explanation.
2+
Also a new example is included to explain sorted()'s basic behavior.

0 commit comments

Comments
 (0)