Python programming language provides a neat syntax to reverse a string, tuple (a read-only list, immutable) or a list (array). The syntax is var[::-1] which returns a reverse copy of the var.
For examples,
1 2 3 4 5 6 | a = [1, 2, 3, 4, 5] print a[::-1] # gives [5, 4, 3, 2, 1] a = “12345” print a[::-1] #gives “54321” a = (1, 2, 3, 4, 5) print a[::-1] #gives (5, 4, 3, 2, 1) |
a = [1, 2, 3, 4, 5] print a[::-1] # gives [5, 4, 3, 2, 1] a = “12345” print a[::-1] #gives “54321” a = (1, 2, 3, 4, 5) print a[::-1] #gives (5, 4, 3, 2, 1)
Simple and effective!
Here are some more ways to reverse a list, tuple or string in Modern Python: Three ways to Reverse a List/Array/Tuple in Python
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
172 wordsloading...
Last Post: Coding Exercise - C++ - Timus - 1787. Turn for MEGA - Online Judge
Next Post: Coding Exercise - Timus Online Judge - 1880. Psych Up's Eigenvalues - C++ solution
thanks