Python Iterate a list in reverse order

Python Iterate a list in reverse order

Here, we will figure out how to repeat a list backward request in Python? To repeat list backwards request we use the list[::- 1] documentation.

Given a list and we need to repeat it in turn around the request in python.

Example:

    Input:
    List = [10, 20, 30, 40, 50]
    Output:
    list = [50, 40, 30, 20, 10]


    Input;
    list = ['Hello', 10 'World', 20]
    Output:
    list = [20, 'World', 10, 'Hello']

Emphasize a list backward request:

To emphasize a list backward request, list[::- 1] is utilized. list[::- 1] will restore the list backward request.

Program:

# define a list
list1  = [10, 20, 30, 40, 50]

# print the list 
print "original list: ", list1

# iterate the list
list1 = list1[::-1]

# print the list 
print "list in reverse order: ", list1

# another list with string and integer elements
list2 = ['Hello', 10, 'world', 20]

# print the list
print "Original list: ", list2

# iterate the list
list2 = list2[::-1]

# print the list
print "list in reverse order: ", list2

Output:

    original list:  [10, 20, 30, 40, 50]
    list in reverse order:  [50, 40, 30, 20, 10]
    Original list:  ['Hello', 10, 'world', 20]
    list in reverse order:  [20, 'world', 10, 'Hello']

Recent Posts

error: Alert: Content is protected!!