Sachin
Posted on September 9, 2023
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)
Output
[3, 5, 67, 3, 4, 2]
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)
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']
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.")
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.
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)
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'
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))
We used the next()
function to access the iterator objects.
Hey
there
geeks
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="")
We used the for
loop to iterate over the reversed sequence and then printed it in a single line.
Greetings from GeekPython
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=" ")
The output will be a reversed tuple and keys of a dictionary.
Greetings from GeekPython
c b a
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()
functionUsage of the Python
reversed()
functionKey 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✌✌
Posted on September 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 1, 2024
October 6, 2024