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

6

Save!

I've been looking for elegant ways to reverse strings, arrays, and integers in Python.

What do you think of my codes below and what do they 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
    
asked by anonymous 28.10.2015 / 00:33

1 answer

6

On this form:

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

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

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

And so, this:

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

In the case of strings , there is still this form:

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

But this form 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 summary, yes, you use the best ways to invert the data structures mentioned.

    
28.10.2015 / 04:53