Effectively list items in tuples starting at the end

I would like to list the elements in a tuple in Python, starting from the back and going forward. Similar to:

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

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

+3
source share
2 answers

You can print tuple(reversed(foo_t))either use listinstead of tupleor

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

and many options. You can also use foo_t[::-1], but I think the built-in is reversedmore readable.

+6
source

First, a general tip: in Python you don't have to write foo_t[len(foo_t)-1]. You can just write foo_t[-1]and Python will go right.

To answer your question, you can 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 is simple:

print(*reversed(foo_t))
+2
source

Source: https://habr.com/ru/post/1741597/


All Articles