31
loading...
This website collects cookies to deliver better user experience
reversed()
**is a built-in function in Python. In this method, we neither modify the original list nor create a new copy of the list. Instead, we will get a reverse iterator which we can use to cycle through all the elements in the list and get them in reverse order, as shown below.# Reversing a list using reversed()
def reverse_list(mylist):
return [ele for ele in reversed(mylist)]
mycountrylist = ['US','India','Germany','South Africa']
mynumberlist = [1,2,3,4,5,6]
print(reverse_list(mycountrylist))
print(reverse_list(mynumberlist))
['South Africa', 'Germany', 'India', 'US']
[6, 5, 4, 3, 2, 1]
mynumberlist = [1,2,3,4,5,6]
newlist = list((reversed(mynumberlist)))
print(newlist)
# Output
# [6, 5, 4, 3, 2, 1]
reverse()
*is a built-in function in Python. In this method, we will not create a copy of the list. Instead, we will modify the original list object *in-place. It means we will copy the reversed elements into the same list. reverse()
method will not return anything as the list is reversed in-place. However, we can copy the list before reversing if required.# Reversing a list using reverse()
def reverse_list(mylist):
mylist.reverse()
return mylist
mycountrylist = ['US','India','Germany','South Africa']
mynumberlist = [1,2,3,4,5,6]
print(reverse_list(mycountrylist))
print(reverse_list(mynumberlist))
['South Africa', 'Germany', 'India', 'US']
[6, 5, 4, 3, 2, 1]
# Reversing a list using slicing technique
def reverse_list(mylist):
newlist= mylist[::-1]
return newlist
mycountrylist = ['US','India','Germany','South Africa']
mynumberlist = [1,2,3,4,5,6]
print(reverse_list(mycountrylist))
print(reverse_list(mynumberlist))
['South Africa', 'Germany', 'India', 'US']
[6, 5, 4, 3, 2, 1]