Write a program to reverse a list in python - Program to reverse a list in python - Python Programs - Pattern programs in python
Program To Reverse A-List
Here's a Python program to reverse a list:
Python Code:
def reverse_list(lst):
"""
Returns a new list that is the reverse of the input list.
"""
return lst[::-1]
Here is the practical of the above program in Jupyter Notebook
# example usage
my_list = [1, 2, 3, 4, 5]
print(reverse_list(my_list)) # [5, 4, 3, 2, 1]
The reverse_list function takes a list as input and returns a new list that is the reverse of the input list. The function does this by using Python's slice notation, which allows you to slice a list with a step value of -1 to reverse it.
Note that this program creates a new list that is the reverse of the input list, rather than modifying the input list in place. If you want to modify the input list in place, you can use the reverse method of the list object:
def reverse_list_in_place(lst):
"""
Modifies the input list in place so that it is reversed.
"""
lst.reverse()
Here is the practical of the above program in Jupyter Notebook
# example usage
my_list = [1, 2, 3, 4, 5]
reverse_list_in_place(my_list)
print(my_list) # [5, 4, 3, 2, 1]
The reverse_list_in_place function takes a list as input and modifies it in place so that it is reversed. The function does this by using the reverse method of the list object. Note that this modifies the input list, rather than creating a new list that is the reverse of the input list.
Comments
Post a Comment