Without using reversed(), how would I loop a set of strings in Python in a function?
Stumbled upon ranges like:
range() and xrange() take a third parameter that specifies a step. So
you can do the following.range(10, 0, -1) Which gives
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] But for iteration, you should really
be using xrange instead. So,xrange(10, 0, -1)
But these don’t really speak to strings?
The function you’re looking for is list comprehensions. These are useful in that you don’t have to iterate over a sequence, which is what
rangeandxrange(in 2.x) provide.strcan be iterated over and sliced, much like strings. The only difference is thatstrelements are immutable.To your example, say you have a set of strings and you want to iterate over them. No problem – just remember that sets have no inherent ordering to them; they only guarantee that the contents are unique.
…which prints:
It’s also the case that you can reverse a single string by itself using the step parameter for a sequence type, of which
strbelongs. You can do that with this:…which prints: