+1 vote
in Programming Languages by (14.9k points)

How can I loop over a sequence in sorted order in Python?

1 Answer

0 votes
by (26.0k points)

To loop over a sequence in sorted order, use the sorted() function. This function returns a new sorted list while leaving the source unchanged.

Example.

>>> aa
['v', 'f', 'm', 'c', 'r', 't', 's', 'a', 't']
>>> for v in sorted(aa):
...     print(v)
...
a
c
f
m
r
s
t
t
v

...