Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
113 views
in Python by (176k points)
How do you sort a list in Python?

Please log in or register to answer this question.

1 Answer

0 votes
by (176k points)

To sort a list in Python, you can use the sort() method. This method modifies the original list in place and sorts its elements in ascending order.

Example:

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort()
print(my_list)
 

Output:

[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
 

In this example, the original list is modified in place and sorted in ascending order.

If you want to sort the list in descending order, you can pass the reverse=True argument to the sort() method:

Example:

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort(reverse=True)
print(my_list)
 

Output:

[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
 

In this example, the original list is modified in place and sorted in descending order.

You can also use the sorted() function to create a new sorted list without modifying the original list:

Example:

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)
print(sorted_list)
 

Output:

[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
 

In this example, a new sorted list is created from the original list, but the original list is not modified.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Mar 20, 2023 in Python by kvdevika (176k points)
+1 vote
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...