Reversing items inside a list

In this blog, we will be using several methods for displaying items in a list in reverse order.

Reverse method.

This method reverses the order of items inside a list.

cars = ['Ford','Volkswagen','Toyota','Honda','Hyundai']
print('Actual order of items in a list')
print(cars)
cars.reverse()
print('Items order after using reverse method')
print(cars)

Output

Actual order of items in a list
['Ford', 'Volkswagen', 'Toyota', 'Honda', 'Hyundai']
Items order after using reverse method
['Hyundai', 'Honda', 'Toyota', 'Volkswagen', 'Ford']

Using for loop to display items in reverse order

Step 1 : Creating a list and finding number of items inside a list using len(). Displaying total number of items in a list

cars = ['Ford','Volkswagen','Toyota','Honda','Hyundai']
print('Actual order of items in a list : ',cars)
le = len(cars)
print('No_of_items : ',le)

Step 2 : Using for loop to display items in a reverse order. Initial value of i = 0 and le = 5. In the print statements, subtracting le from 1 (5-1=4). This is last index number in a list. Displaying the value of last index number.

for i in  range (l) :
    print(cars[l-1])
    l = l -1

Output

Actual order of items in a list :  ['Ford', 'Volkswagen', 'Toyota', 'Honda', 'Hyundai']
No_of_items :  5
Hyundai
Honda
Toyota
Volkswagen
Ford

Complete Code

cars = ['Ford','Volkswagen','Toyota','Honda','Hyundai']
print('Actual order of items in a list : ',cars)
l = len(cars)
print('No_of_items : ',l)
for i in  range (l) :
    print(cars[l-1])
    l = l -1

Using empty list for storing values of a actual list in reverse order.

cars = ['Ford','Volkswagen','Toyota','Honda','Hyundai']
print('Actual order of items : ',cars)
l = len(cars)
print('No_of_items : ',l)
cars_2 = []
for i in  range (l) :
    cars_2.insert(i,cars[l-1])
    l = l -1

print('Reverse order of items : ',cars_2)

Output

Actual order of items :  ['Ford', 'Volkswagen', 'Toyota', 'Honda', 'Hyundai']
No_of_items :  5
Reverse order of items :  ['Hyundai', 'Honda', 'Toyota', 'Volkswagen', 'Ford']

In the above code, we have used empty list cars_2 and assign values from cars list in a reverse order

Leave a Reply

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 )

Google photo

You are commenting using your Google 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