Four Ways to Reverse the String/List














































Four Ways to Reverse the String/List



# Reverse The List Itself.
testList = [1, 3, 5]
testList.reverse()
print(testList)

=> [5, 3, 1]

# Reverse While Iterating In A Loop.
for element in reversed([1,3,5]): print(element)

#1-> 5
#2-> 3
#3-> 1

# Reverse A String In Line.
"Cpp secrets"[::-1]
This gives the output as "sterces ppC"

# Reverse A List Using Slicing.
[1, 3, 5][::-1]
The above command will give the output as [5, 3, 1].

Comments