We provide effective and economically affordable training courses for R and Python, Click here for more details and course registration !

When a list is created in Python, the order of its element contained can be sorted in alphabetical order later. There are mainly two functions for sorting a list in Python. sort() function will sort a list’s elements permanently. If you just want to sort a list temporarily, you can use sorted() function.

  1. In the following example, a list ‘motors’ is created first. Then the elements of the list is sorted alphabetically.
#create a list first
motors = ['VOLVO', 'Isuzu', 'QQ', 'SAAB']
#the list is sorted
motors.sort()
#print the list again, we can see the order of elements are sorted
#alphabetically, and it can not be returned to its original order any more
print(motors)

#output
['Isuzu', 'QQ', 'SAAB', 'VOLVO']

The list can be sorted alphabetically in reverse order, by setting the option reverse is True.

#to create a list first
motors = ['VOLVO', 'Isuzu', 'QQ', 'SAAB']
#to sort the elements of the list alphabetically, in reverse order
motors.sort(reverse=True)
print(motors)

#output
['VOLVO', 'SAAB', 'QQ', 'Isuzu']

2. If you just want to sort a list temporarily for some operation, then the function sorted() can be applied. The following example show an example for that.

#to create a list first
motors = ['VOLVO', 'Isuzu', 'QQ', 'SAAB']
#sort the list temporarily, in alphabetical order
print("\nsorted alphabetically:")
print(sorted(motors))
#output
sorted alphabetically:
['Isuzu', 'QQ', 'SAAB', 'VOLVO']

#to sort temporarily in reverse alphabetical order
print("\nsorted in reverse alphabetical list:")
print(sorted(motors, reverse=True))
#output
sorted in reverse alphabetical list:
['VOLVO', 'SAAB', 'QQ', 'Isuzu']

#to show the original list again
print("\nshow the original list again:")
print(motors)
#output
show the original list again:
['VOLVO', 'Isuzu', 'QQ', 'SAAB']

You can see that sorted() function will not change the order of the list permanently.

3. Another frequently used function relating to the order of a list , is reverse(). This function is just reverse the order of a list permanently.

#to create a list
motors = ['VOLVO', 'Isuzu', 'QQ', 'SAAB']
#reverse the order of elements of the list
motors.reverse()
#to show the list again
print(motors)
#output
['SAAB', 'QQ', 'Isuzu', 'VOLVO']

You can also watch full video for Python tutorial for more examples of data management from our YouTube channel.


0 Comments

Leave a Reply

Avatar placeholder