0

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?

3
  • 1
    A set has no inherent ordering, so the concept of iterating over a set “in reverse” doesn't make sense. Do you mean a list of strings? Commented Dec 2, 2012 at 2:51
  • "But these don't really speak to strings?" You could try and see Commented Dec 2, 2012 at 2:51
  • 1
    This question is vague. Can you show some code? Sample input and desired output? Do you really have a "set of strings" or are you using "set" casually? Commented Dec 2, 2012 at 2:59

2 Answers 2

3

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 range and xrange (in 2.x) provide.

str can be iterated over and sliced, much like strings. The only difference is that str elements 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.

myset = set(["first", "second", "third", "fourth", "fifth"])
for i in myset:
    print i

...which prints:

second
fifth
fourth
third
first

It's also the case that you can reverse a single string by itself using the step parameter for a sequence type, of which str belongs. You can do that with this:

"this is the song that never ends"[::-1]

...which prints:

'sdne reven taht gnos eht si siht'
Sign up to request clarification or add additional context in comments.

1 Comment

Makoto got what I was looking for. Yeah, I was using the word set more casually! Thanks all!
1

try this:

>>> str = 'abcdefghijklmnopqrstuvwxyz'
>>> str[::-1]
'zyxwvutsrqponmlkjihgfedcba'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.