We need sorted() function to sort the given list in ascending or descending order.
The syntax is as follows: sorted(list, key=..., reverse=....)
>> Lets see first list sorting:-
#First we need to specify an array and save it in a variable.
a = [2.2, 2.3233, 2322, 32.23, 2, 32.2, 5.11, 4, 0.1, 0.1]
#Secondly we'll be using a sorted() function to sort out the given array.
print('sorting in ascending order:', sorted(a))
#Lastly we'll be using reverse=True for the array to be in descending order.
print('sorting in descending order:', sorted(a, reverse = True))
#Output:
sorting in ascending order: [0.1, 0.1, 2, 2.2, 2.3233, 4, 5.11, 32.2, 32.23, 2322]
sorting in descending order: [2322, 32.23, 32.2, 5.11, 4, 2.3233, 2.2, 2, 0.1, 0.1]
>> Then lets see set{} sorting:-
a = {2.2, 2.3233, 2322, 32.23, 2, 32.2, 5.11, 4, 0.1, 0.1}
#Output:[0.1, 0.1, 2, 2.2, 2.3233, 4, 5.11, 32.2, 32.23, 2322]
>> Tuple() sorting:-
a = (2.2, 2.3233, 2322, 32.23, 2, 32.2, 5.11, 4, 0.1, 0.1)
#Output:[0.1, 0.1, 2, 2.2, 2.3233, 4, 5.11, 32.2, 32.23, 2322]
>> Dictionary{:1, :2} sorting:-
a = {2.2:1, 2.3233:2, 2322:3, 32.23:4, 2:5, 32.2:6, 5.11:7, 4:8, 0.1:9, 0.1:10}
#Output:[0.1, 0.1, 2, 2.2, 2.3233, 4, 5.11, 32.2, 32.23, 2322]
>> Then sorting a string:-
b = 'python is a programming language!'
print(sorted(b))
#Output: [' ', ' ', ' ', ' ', '!', 'a', 'a', 'a', 'a', 'e', 'g', 'g', 'g', 'g', 'h', 'i', 'i', 'l', 'm', 'm', 'n', 'n', 'n', 'o', 'o', 'p', 'p', 'r', 'r', 's', 't', 'u', 'y']
Note: If we sort a string then it will be sorted in alphabetical order, first privilege is given to blank space and special characters.
Comments
Post a Comment