d-cubed
d-cubed

Reputation: 1112

efficiently list items in tuples starting at end

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?

Upvotes: 3

Views: 150

Answers (2)

Daniel Stutzbach
Daniel Stutzbach

Reputation: 76727

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))

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 882171

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.

Upvotes: 6

Related Questions