Python Program to Sort a List In Different Ways | Python Examples

#JavaInspires

 Hi Guys,

In this post, we will see how to sort a list in different ways(basic).

Here we will create a list with county names : country_list.

Then we will sort this in normal order, reverse order, temporary sort and so on.


Program:


#create a simple list contains country names
country_list = ['US','Canada','Mexico','UK','Italy','India','China']
#print this list
print("Original List \n",country_list)
#Sorting a List Temporarily with the sorted() Function
print("sorted(country_list) \n",sorted(country_list))
print("Original List \n",country_list)
print("sorted(country_list,reverse=True) \n",sorted(country_list,reverse=True))
print("Original List \n",country_list)
#Sorting a List Permanently with the sort() Method
country_list.sort()
#print this list
print("country_list.sort() \n",country_list)
#reverse=True to the sort() method
country_list.sort(reverse=True)
#print this list
print("country_list.sort(reverse=True) \n",country_list)




Original List 
 ['US', 'Canada', 'Mexico', 'UK', 'Italy', 'India', 'China']
sorted(country_list) 
 ['Canada', 'China', 'India', 'Italy', 'Mexico', 'UK', 'US']
Original List 
 ['US', 'Canada', 'Mexico', 'UK', 'Italy', 'India', 'China']
sorted(country_list,reverse=True) 
 ['US', 'UK', 'Mexico', 'Italy', 'India', 'China', 'Canada']
Original List 
 ['US', 'Canada', 'Mexico', 'UK', 'Italy', 'India', 'China']
country_list.sort() 
 ['Canada', 'China', 'India', 'Italy', 'Mexico', 'UK', 'US']
country_list.sort(reverse=True) 
 ['US', 'UK', 'Mexico', 'Italy', 'India', 'China', 'Canada']



#JavaInspires

1 Comments

Previous Post Next Post