Programmers learn & share
0 votes

Problem :

I need solution for below problem using Python

Given that play_list has been defined to be a list, write a statement that sorts the list.

by (7.5k points)   | 79 views

2 Answers

0 votes


I have faced the same Problem in the recent past. I have the  following solution on your problem.

Depending on the contents of list, there different approaches and they can be used according to need. In the easiest possible case, when the play_list is considered the list of integers or strings, the sorted() function must be used as follows:

 play_list = [3, 1, 2, 5, 4]

sorted_play_list = sorted(play_list)

 print(sorted_play_list) # [1, 2, 3, 4, 5]


play_list = ['cdgf', 'fs', 'aa', 'Zsdf', 'qvtr', 'fa']

sorted_play_list = sorted(play_list)

print(sorted_play_list) # ['Zsdf', 'aa', 'cdgf', 'fa', 'fs', 'qvtr']

 If the contents of play_list are complex objects e.g. lists or class object  the key parameter must  be specified that will be used for comparisons as follows:

play_list = [[2, 'b'],[1, 'c'],[3, 'a']]

# sort by second element of nettled list

sorted_play_list = sorted(play_list, key=lambda a: a[1])

print(sorted_play_list) # [[3, 'a'], [2, 'b'], [1, 'c']]

So I will suggest the following approaches:

1) If the elements are atomic, then you can use sorted(play_list);

2) If the elements are complex, then you can use sorted(play_list, key=key)

by (36.1k points)  
0 votes


The sort() method sorts the elements of a given list.

The sort() method sorts the elements of a given list in a specific ascending or descending order.

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's built-in sorted() function for the same purpose.

sorted(list, key=..., reverse=...)

Example: sort a given list

# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels

# print vowels
print('Sorted list:', vowels)

Sorting user using user defined order.

list_name.sort(key=…, reverse=…) – it sorts according to user’s choice
# Python program to demonstrate sorting by user's 
# choice 

# function to return the second element of the 
# two elements passed as the parameter 
def sortSecond(val): 
	return val[1] 

# list1 to demonstrate the use of sorting 
# using using second key 
list1 = [(1, 2), (3, 3), (1, 1)] 

# sorts the array in ascending according to 
# second element 
list1.sort(key = sortSecond) 

# sorts the array in descending according to 
# second element 
list1.sort(key = sortSecond, reverse = True) 


by (12.8k points)  
2,245 questions
2,807 answers
241 users