views:

62

answers:

2

I'd like to list the items in a tuple in Python starting with the back and go to front. Similar to:

foo_t = tuple(int(f) for f in foo)
print foo, foo_t[len(foo_t)-1] ...

I believe this should be possible without Try ...-4, except ...-3. Thoughts? suggestions?

+7  A: 

You can print tuple(reversed(foo_t)), or use list in lieu of tuple, or

print ' '.join(str(x) for x in reversed(foo_t))

and many variants. You could also use foo_t[::-1], but I think the reversed builtin is more readable.

Alex Martelli
Wow. I'm always impressed by the number of things Python has built in. This worked out well. Thank you.
Donnied
+2  A: 

First, a general tip: in Python you never need to write foo_t[len(foo_t)-1]. You can just write foo_t[-1] and Python will do the right thing.

To answer your question, you could do:

for foo in reversed(foo_t):
    print foo, # Omits the newline
print          # All done, now print the newline

or:

print ' '.join(map(str, reversed(foo_t))

In Python 3, it's as easy as:

print(*reversed(foo_t))
Daniel Stutzbach
foo_t[len(foo_t)-1] -- oops I guess I was getting jumbled as I was writing. I was thinking of how to comparing some count with < len(foo_t). Thank you.
Donnied