+2 votes
in Programming Languages by (73.8k points)

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

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

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


...