Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Pandas Series.sort_values()
Next article icon

How to Sort a Set of Values in Python?

Last Updated : 04 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting means arranging the set of values in either an increasing or decreasing manner. There are various methods to sort values in Python. We can store a set or group of values using various data structures such as list, tuples, dictionaries which depends on the data we are storing. We can sort values in Python using built-in functions like sorted() or by using the sort() method for lists.

Sorted() Method

sorted() function is a built-in Python function that returns a new sorted list from the elements of any iterable, such as a list, tuple or string. The original iterable remains unchanged.

Example 1: Sorting Different Data Types Using sorted()

This example demonstrates how to sort different types of data structures like lists, tuples, strings, dictionaries, sets and frozen sets using the sorted() function.

Python
# List a = ['g', 'e', 'e', 'k', 's'] print(sorted(a))  # Tuple tup = ('g', 'e', 'e', 'k', 's') print(sorted(t))  # String-sorted based on ASCII translations a = "geeks" print(sorted(a))  # Dictionary d = {'g': 1, 'e': 2, 'k': 3, 's': 4} print(sorted(d))  # Set s = {'g', 'e', 'e', 'k', 's'} print(sorted(s)) frozen_set = frozenset(('g', 'e', 'e', 'k', 's')) print(sorted(frozen_set)) 

Output
['e', 'e', 'g', 'k', 's'] ['e', 'e', 'g', 'k', 's'] ['e', 'e', 'g', 'k', 's'] ['e', 'g', 'k', 's'] ['e', 'g', 'k', 's'] ['e', 'g', 'k', 's'] 

Explanation: The sorted() function returns a new sorted list from the iterable provided. It works with any iterable object and sorts them based on their natural order. For dictionaries, the keys are sorted and for sets and frozen sets, the unique elements are sorted.

Example 2: Using predefined function as key-parameter

This code shows how to use the key parameter with a predefined function (len()) to sort a list of strings based on their length.

Python
a = ["apple", "ball", "cat", "dog"]  print("without key parameter:", sorted(a)) print("with len as key parameter:", sorted(a, key=len)) 

Output
without key parameter: ['apple', 'ball', 'cat', 'dog'] with len as key parameter: ['cat', 'dog', 'ball', 'apple'] 

Explanation: The key parameter is used to specify a function to be applied to each element before sorting. Here, the len() function is used to sort a list of strings based on their lengths. The output is sorted by the number of characters in each string rather than by the lexicographical order of the strings.

Example 3: Using the user-defined function for the key parameter

This example explains how to use the key parameter with custom user-defined functions to sort a list of tuples based on either the name or the marks.

Python
a = [("Ramesh",56),("Reka",54),("Lasya",32),("Amar",89)]  # defining a user-defined function which returns the first item(name)  def by_name(ele):   return ele[0]  # defining a user-defined function which returns the second item(marks)  def by_marks(ele):   return ele[1]  print("without key parameter:", sorted(a))  print("with by_name as key parameter:", sorted(a, key=by_name))  print("with by_marks as key parameter:", sorted(a, key=by_marks)) 

Output

without key parameter: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with by_name as key parameter: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with by_marks as key parameter: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]

Explanation: In this code, the sorted() function is used with user-defined functions (by_name and by_marks) passed through the key parameter. This allows us to customize how sorting is done based on specific attributes. In this example, a list of tuples containing student names and marks is sorted first by the name (alphabetically) and then by the marks (numerically).

Example 4: Using reverse Parameter

This example demonstrates how to use the reverse=True parameter to sort data in descending order, along with the regular sorted() function.

Python
a = ["geeks","for","geeks"]  print("without key parameter:", sorted(a))  print("with len as key parameter:", sorted(a, reverse=True)) 

Output
without key parameter: ['for', 'geeks', 'geeks'] with len as key parameter: ['geeks', 'geeks', 'for'] 

Explanation: reverse parameter is demonstrated in the sorted() function. When reverse=True, the function sorts the data in descending order instead of the default ascending order. This example sorts a list of strings in reverse order based on their lexicographical order, meaning that the list is ordered from Z to A instead of A to Z.

Example 5: Using key and reverse Parameters

This example combines the use of both key and reverse parameters to sort data based on user-defined functions with the option to sort in ascending or descending order.

Python
a = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]  # defining a user-defined function which returns the first item(name) def by_name(ele):     return ele[0]  # defining a user-defined function which returns the second item(marks) def by_marks(ele):     return ele[1]  print("without key and reverse:", sorted(a))  print("with key and reverse parameter:", sorted(a, key=by_name, reverse=False)) print("with key and reverse parameter:", sorted(a, key=by_name, reverse=True))  print("with key and reverse parameter:", sorted(a, key=by_marks, reverse=False)) print("with key and reverse parameter:", sorted(a, key=by_marks, reverse=True)) 

Output

without key and reverse: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with key parameter and reverse parameter: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with key parameter and reverse parameter: [('Reka', 54), ('Ramesh', 56), ('Lasya', 32), ('Amar', 89)]
with key parameter and reverse parameter: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]
with key parameter and reverse parameter: [('Amar', 89), ('Ramesh', 56), ('Reka', 54), ('Lasya', 32)]

Explanation: This example combines both the key and reverse parameters in the sorted() function. The key parameter allows sorting based on a custom criterion (like student names or marks) and the reverse parameter allows for sorting in descending order. By using both, the list of student tuples can be sorted by name or marks, in ascending or descending order, depending on the specified flags.

Sort() Method

sort() method is a list method that sorts the list in place. Unlike the sorted() function, it does not return a new list but modifies the original list.

Example 1: Basic List Sorting Using sort()

This example demonstrates how to sort a list of strings in ascending order using Python's sort() method. It modifies the list in place.

Python
a = ["geeks", "for", "geeks"]  # using the sort method to sort the items a.sort()  print("Sorted list:", a) 

Output
Original list: ['geeks', 'for', 'geeks'] Sorted list: ['for', 'geeks', 'geeks'] 

Explanation: The sort() method sorts the items of the list in lexicographical (alphabetical) order. Since no key or reverse parameter is provided, it performs a default ascending order sort. The sorting is done directly on the original list, meaning no new list is created.

Example 2: Using a predefined function as the key parameter

This example demonstrates how to sort a list of strings based on their length using the key parameter with the predefined len() function.

Python
a = ["apple", "ball", "cat", "dog"]  # using the len() as key parameter and sorting the list a.sort(key=len) print("Sorting with len as key parameter:", a) 

Output
Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple'] 

Explanation: In this example, the sort() method is used with the key parameter, where key=len sorts the list based on the length of each string. The key parameter tells Python to compare the items by their length rather than their value. This results in sorting the list from the shortest string to the longest.

Example 3: Using a user-defined function as the key parameter

This code demonstrates sorting a list of tuples by custom criteria: the student’s name and marks, using user-defined functions for sorting.

Python
def by_name(ele):     return ele[0]  # defining a user-defined function which returns the second item(marks) def by_marks(ele):     return ele[1]      a = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]  # sorting by key value as by_name function a.sort(key=by_name) print(a)  a = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]  # sorting by key value as by_marks function a.sort(key=by_marks) print(a) 

Output:

[('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
[('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]

Explanation: In this example, the sort() method uses a key parameter that is set to user-defined functions. The function by_name sorts the list of tuples by the first element (the name) and the function by_marks sorts by the second element (the marks). This allows sorting based on the desired attribute, either name or marks.

Example 4: Using reverse parameter

This code illustrates how to sort a list in descending order using the reverse=True parameter.

Python
a = ["geeks", "for", "geeks"]  a.sort(reverse=True) print("with reverse parameter", a) 

Output
with reverse parameter ['geeks', 'geeks', 'for'] 

Explanation: The sort() method with reverse=True sorts the list in descending order. This means the largest elements come first and the smallest elements come last. It modifies the original list and sorts it in place. The reverse parameter effectively reverses the result of the default ascending order sort.


Next Article
Python | Pandas Series.sort_values()

M

magichat
Improve
Article Tags :
  • Sorting
  • Python
  • DSA
Practice Tags :
  • python
  • Sorting

Similar Reads

  • Python | Pandas Series.sort_values()
    Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.sort_values() function is use
    2 min read
  • Python | Pandas Dataframe.sort_values() | Set-2
    Prerequisite: Pandas DataFrame.sort_values() | Set-1 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. Pandas sort_values() function so
    3 min read
  • Python | Pandas Index.sort_values()
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.sort_values() function is used to sort the index values. The function ret
    2 min read
  • Sort a list in Python without sort Function
    Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sor
    3 min read
  • How To Sort The Elements of a Tensor in PyTorch?
    In this article, we are going to see how to sort the elements of a PyTorch Tensor in Python. To sort the elements of a PyTorch tensor, we use torch.sort() method.  We can sort the elements along with columns or rows when the tensor is 2-dimensional. Syntax: torch.sort(input, dim=- 1, descending=Fals
    3 min read
  • How to Sort a list in Scala?
    Sorting a list is a common operation in programming, and Scala provides convenient ways to accomplish this task. In this article, we'll explore different methods to sort a list in Scala, along with examples. Table of Content Using the sorted Method:Using the sortBy Method:Using the sortWith Method:S
    2 min read
  • Tag sort or Bucket sort or Bin sort in Python
    Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in
    2 min read
  • Python - Sort words of sentence in ascending order
    Sorting words in a sentence in ascending order can be useful for tasks like text analysis, data preprocessing, or even fun applications like creating word puzzles. It’s simple to achieve this using Python. In this article, we will explore different methods to do this. Using sorted() with SplitThe mo
    3 min read
  • Sort Python Dictionary by Key or Value - Python
    There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary b
    6 min read
  • Tree Sort in Python
    Tree sort is a sorting algorithm that builds a Binary Search Tree (BST) from the elements of the array to be sorted and then performs an in-order traversal of the BST to get the elements in sorted order. In this article, we will learn about the basics of Tree Sort along with its implementation in Py
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences