Program to display elements inside a list in reverse order

This blog explain how to display elements in a list in reverse order

Creating a number list from 1 to 8 and displaying original order of each element using for loop

num = [1,2,3,4,5,6,7,8]
print('Original order of elements in a list')
for n in num:
    print(n)

Finding total of number of elements in a list using len()

len = len(num)
print('Total number of elements in a list : %d'%len)

Positive index starts with 0 and negative index starts with -1

To display last element of a list use index value -1 and to display second last element use index value -2 and so on

Below is the table which gives positive and negative index position of elements

Items12345678
Positive Index01234567
Negative Index-8-7-6-5-4-3-2-1

Creating a variable and assigning initial value of 1

counter = 1

Using while loop to display elements of a list in reverse order. Negative index (-counter) is use to display elements from last to first order

while counter <= len:
    print(num[-counter])
    counter += 1

Output

Original order of elements in a list
1
2
3
4
5
6
7
8
Total number of elements in a list : 8
Revering order of elements in a list
8
7
6
5
4
3
2
1

Complete Code

num = [1,2,3,4,5,6,7,8]
print('Original order of elements in a list')
for n in num:
    print(n)
len = len(num)
print('Total number of elements in a list : %d'%len)
counter = 1
print('Revering order of elements in a list')
while counter <= len:
    print(num[-counter])
    counter += 1

Example 2 : Displaying elements in a country list in reverse order

countries = ['India','UK','France','USA','Australia','Singapore']
print('Original order of elements in a list')
for c in countries:
    print(c)
len = len(countries)
print('\n')
print('Total number of elements in a list : %d\n'%len)
counter = 1
print('Reverse order of elements in a list')
while counter <= len:
    print(countries[-counter])
    counter += 1

Output

Original order of elements in a list
India
UK
France
USA
Australia
Singapore


Total number of elements in a list : 6

Reverse order of elements in a list
Singapore
Australia
USA
France
UK
India

Below table gives positive and negative index position of each element

ItemsIndiaUKFranceUSAAustraliaSingapore
Positive Index012345
Negative Index-6-5-4-3-2-1

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s