DEV Community

Cover image for What is the Difference Between Reverse and Reversed in Python
Sachin
Sachin

Posted on • Originally published at geekpython.in

What is the Difference Between Reverse and Reversed in Python

Lists are one of the in-built data types in Python used to store the collections of data. It is used to work with a sequence of data. Besides data types, Python has numerous standard functions for performing specific tasks.

Python lists are probably the first data type that most Python beginners start learning in a sequence category, and along with this, their functions and methods. The reverse() function is one of the functions of Python Lists used to reverse the elements from the list.

To get the same work done, Python has a function named reversed(), which is also used to reverse the sequence of data.

In this article, we will deep dive into both functions and understand their fundamentals and usage along with examples, and then at the end of this article, we'll point out the differences between them.

List reverse() function

As we discussed earlier, the reverse() function from Python List is used to reverse the elements in a List. This function does what its name depicts itself.

The list reverse() function operates on the original list. It reverses the list and then returns it. If we try to print the original list, we'll get the reversed list because the original list no longer exists, and the reversed list is the original.

my_lst = [2, 4, 3, 67, 5, 3]
my_lst.reverse()

print(my_lst)
Enter fullscreen mode Exit fullscreen mode

Output

[3, 5, 67, 3, 4, 2]
Enter fullscreen mode Exit fullscreen mode

We tried to print the original list, but due to the use of the reverse() function, our list got modified, and we got the reversed list.

Syntax - reverse()

list.reverse()

Parameter

There are no parameters, and neither it takes any arguments.

Return Value

It does not return any value but reverses the elements from the list.

Usage - reverse()

We have two lists in the following example, the first list has collections of integers, and the second contains multiple data types.

# List of numbers
lst1 = [2, 4, 3, 67, 5, 3]
lst1.reverse()
print('First List: ', lst1)

# List containing multiple data types
lst2 = ['a', 2, 'w', 'u', 3j+1]
lst2.reverse()
print('Second List: ', lst2)
Enter fullscreen mode Exit fullscreen mode

We used the reverse() function on both lists and got the output as we expected it should be.

First List:  [3, 5, 67, 3, 4, 2]
Second List:  [(1+3j), 'u', 'w', 2, 'a']
Enter fullscreen mode Exit fullscreen mode

We put the reverse() function to practical use in the following example when we check whether a specified value is a palindrome.

# Creating a list from a string
lst = list('malayalam')

# Creating a copy of the original list
new_lst = lst.copy()
# Reversing
new_lst.reverse()

# Comparing the lists
if lst == new_lst:
    print("It's a Palindrome.")
else:
    print("Not a Palindrome.")
Enter fullscreen mode Exit fullscreen mode

The value "malayalam" is a palindrome because it will remain the same whether we reverse it or not. That's why we got the output "It's a Palindrome" because the original and reversed lists are the same.

It's a Palindrome.
Enter fullscreen mode Exit fullscreen mode

What will happen if we try to reverse a string? In the above example, we specified the string but converted it into the list before performing the reverse operation.

# Defining a String
my_str = "geekpython"
# Trying to reverse a string
my_str.reverse()

print(my_str)
Enter fullscreen mode Exit fullscreen mode

We'll get an error if we use the reverse() function on a string.

Traceback (most recent call last):
  File "D:\SACHIN\Pycharm\reverse_vs_reversed\main.py", line 28, in <module>
    my_str.reverse()
AttributeError: 'str' object has no attribute 'reverse'
Enter fullscreen mode Exit fullscreen mode

The error says that the string has no attribute reverse. We cannot use the reverse function on the string data type or any other data type. The reverse() function can only be used for the list data type.

Python reversed() function

Python reversed() function takes a sequence and returns the reversed iterator object. It is the same as the iter() method but in reverse order. We can access the reversed objects either by iterating them or using the next() function.

# Defining a list
my_lst = ['geeks', 'there', 'Hey']

# Calling the reversed() function on the original list
new_lst = reversed(my_lst)
# Accessing the reversed objects one by one
print(next(new_lst))
print(next(new_lst))
print(next(new_lst))
Enter fullscreen mode Exit fullscreen mode

We used the next() function to access the iterator objects.

Hey
there
geeks
Enter fullscreen mode Exit fullscreen mode

Syntax - reversed()

reversed(sequence)

Parameter

  • sequence - Any sequence object that is iterable.

Return Value

Returns the reversed iterator object of the given sequence.

Usage - reversed()

We have already seen the example where we performed the reverse operation on the Python list using the reversed() function. This time we'll try to reverse the Python string.

my_str = "nohtyPkeeG morf sgniteerG"

for rev_str in reversed(my_str):
    print(rev_str, end="")
Enter fullscreen mode Exit fullscreen mode

We used the for loop to iterate over the reversed sequence and then printed it in a single line.

Greetings from GeekPython
Enter fullscreen mode Exit fullscreen mode

Similarly, we can use any sequence object that is iterable. List, Tuple, and Dictionary objects are iterable and can be reversed. The Set objects can also be iterated but they are not reversible.

# Defining a Tuple
my_tup = ("GeekPython", "from", "Greetings")
# Defining a Dictionary
my_dict = {"a": 1, "b": 0, "c": 7}

# Reversing a Tuple
for rev_tup in reversed(my_tup):
    print(rev_tup, end=" ")
print("\n")

# Reversing a Dictionary
for rev_dict in reversed(my_dict):
    print(rev_dict, end=" ")
Enter fullscreen mode Exit fullscreen mode

The output will be a reversed tuple and keys of a dictionary.

Greetings from GeekPython 

c b a
Enter fullscreen mode Exit fullscreen mode

What's the difference?

We've seen the definition and usage of both functions and are now able to differentiate between them. The primary work of both functions is to reverse the objects of the given sequence. But there are some key differences between the reverse() and reversed() functions which are listed below.

reverse() reversed()
The reverse() function can only reverse the Python list. The reversed() function can be used to reverse lists, tuples, strings, and dictionaries, or any iterable sequence.
Returns the reversed sequence. Returns the reversed iterator object of the sequence.
Operates on the original list and modifies it. Creates the iterator object from the original sequence and the original sequence remains the same.
Takes no arguments. Any sequence that is iterable is required.

Conclusion

This article covered the fundamentals and usage of the reverse() and reversed() functions and we coded some examples along with them. Through this article, we meant to dive into the working and usage of the functions and of course, point out the key differences between them.

Let's review what we've learned:

  • Usage of list reverse() function

  • Usage of the Python reversed() function

  • Key differences between both functions


๐Ÿ†Other articles you might be interested in if you liked this one

โœ…How to read multiple files simultaneously using fileinput module?

โœ…Number the iterable objects using the enumerate() function in Python.

โœ…What is the difference between seek and tell in Python?

โœ…How do bitwise operators work behind the scenes in Python?

โœ…What are args and kwargs parameters within the function in Python?

โœ…Asynchronous programming in Python using asyncio module.

โœ…Create a virtual environment to create an isolated space for projects in Python.


That's all for now

Keep CodingโœŒโœŒ

Top comments (2)

Collapse
 
ranggakd profile image
Retiago Drago

Itโ€™s interesting to see how these two functions can be used in different situations to achieve similar results. Understanding their differences can help you choose the right one for your needs! ๐Ÿ˜Š

Collapse
 
sachingeek profile image
Sachin

โค