More elegant ways to invert integers, arrays and strings in Python

Asked

Viewed 900 times

6

Hail!

I’ve been looking for elegant ways to do string inversion, arrays and integers in Python.

What do you think of my codes below and what suggest to improve them? They work...

Thank you!

frase = 'eu gosto de python'[::-1]
numero = [12, 13, 14, 15, 16, 17]
inteiro = 123456
numeroInvertido = int(str(inteiro)[::-1])
print frase
print numero [::-1]
print numeroInvertido
  • Hello, welcome to [en.so]! The solutions seem reasonable to me - although I’m not a Python expert. But perhaps it would be good to explain what exactly you intend to do with the inverted values. For example, if the idea is just to iterate once over a reversed list it might not be very efficient to duplicate the list in memory.

1 answer

6


About this form:

frase = 'eu gosto de python'[::-1]

Not only is it the most performative but also the fastest for all cases. This is also true for this form:

numero = [12, 13, 14, 15, 16, 17][::-1]

And so this:

numeroInvertido = int(str(inteiro)[::-1])

In case strings, there’s still this way:

''.join(reversed('eu gosto de python'))

But this way is slower.

For lists, you can still do:

list(reversed([12, 13, 14, 15, 16, 17]))

Also slower. Or even:

numero = [12, 13, 14, 15, 16, 17]
print(numero.reverse())

In short, yes, you use the best ways to reverse the data structures mentioned.

  • And to invert the digits of an integer? Treating string is also the best solution?

  • Without using mathematics, it is the best solution. I can put this observation in the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.