Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Hosted By
Ryan Valles
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
How you can accelerate your learnings

The sorted() Function in Python

Python supports object-oriented programming and has a concise, readable, and easy-to-learn syntax. It is no wonder that it is one of the most popular programming languages. An integral part of Python are its built-in functions. You would have surely used some of these functions in your programs. 

We've written a series of articles to help you learn and brush up on the most useful Python functions. In this article, we’ll learn about Python's sorted() function and how to use it. 

If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Python Exit commands, and Type and Isinstance In Python for more content on Python coding interview preparation.

Having trained over 10,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll cover:

  • What Is the sorted() Function in Python and What Does It Do?
  • The sorted() Function in Python: Syntax
  • The sorted() Function in Python: Example
  • FAQs on the sorted() Function in Python

What Is the sorted() Function in Python and What Does It Do?

Python sorted() function returns a sorted list with elements taken from an iterable object. The sorted() function sorts any sequence, like a tuple or a list, and always returns a list with the elements in sorted order. If you’re wondering how to sort a list in Python without the sort() function, sorted() is a way to go. Note that sorted() does not modify the original sequence. 

The sorted() Function in Python: Syntax


Syntax: sorted(iterable, key, reverse)

The sorted() function in Python takes three parameters, out of which two are optional:

  • Iterable: It’s a sequence like a list, tuple, and string, or a collection like a dictionary, set, and frozen set, or any other iterator that we need to sort.
  • Key (optional): A function to serve as a key/basis of sort comparison. It takes a value “a” and returns another value “b,” where “b” is the function’s evaluation of “a.” This other value, b, is then used in sorted(), not the original value, a. For example, specifying key=len when passing a list of strings in sorted(), instead of getting sorted alphabetically, the value len returns, which is the length of strings (the basis on which the strings are sorted).
  • Reverse (optional): A boolean that, when set true, the iterable is sorted in reverse or descending order. Its default value is set to false.

The sorted() Function in Python: Example

Here, we take a look at how you can use the Python function sorted() next time you need it:

Code


listExample = ["deer", "banana", "cat", "elephant", "flower", "apple"]

# Showing the working of sorted() using a list as an example
print(listExample)
print("After sorting list using sorted: ")
print(sorted(listExample))
 
print("\nAfter sorting list in reverse using sorted: ")
print(sorted(listExample, reverse=True))

print("\nAfter sorting list on the basis of function len using sorted: ")
print(sorted(listExample, key=len))

print("\nAfter sorting list on the basis of function len in reverse using sorted: ")
print(sorted(listExample, key=len, reverse=True))

print("\nChecking the original list is still not modified: ")
print(listExample)

# Showing the working of sorted() in tuple, dictionary, set and frozen set
print("\nSorting different iterable types using sorted: ")
# Tuple
tupleExample = ("deer", "banana", "cat", "elephant", "flower", "apple")
print(sorted(tupleExample))
 
# String/ASCII sort
stringExample = "fruits"
print(sorted(stringExample))
 
# Dictionary
dictExample = {'b': 2, 'd': 4, 'f': 6, 'h': 8, 'j': 10, 'i': 0}
print(sorted(dictExample))
 
# Set
setExample = {"deer", "banana", "cat", "elephant", "flower", "apple"}
print(sorted(setExample))
 
# Frozen Set
frozensetExample = frozenset(("deer", "banana", "cat", "elephant", "flower", "apple"))
print(sorted(frozensetExample))

Output


['deer', 'banana', 'cat', 'elephant', 'flower', 'apple']
After sorting list using sorted: 
['apple', 'banana', 'cat', 'deer', 'elephant', 'flower']

After sorting list in reverse using sorted: 
['flower', 'elephant', 'deer', 'cat', 'banana', 'apple']

After sorting list on the basis of function len using sorted: 
['cat', 'deer', 'apple', 'banana', 'flower', 'elephant']

After sorting list on the basis of function len in reverse using sorted: 
['elephant', 'banana', 'flower', 'apple', 'deer', 'cat']

Checking the original list is still not modified: 
['deer', 'banana', 'cat', 'elephant', 'flower', 'apple']

Sorting different iterable types using sorted: 
['apple', 'banana', 'cat', 'deer', 'elephant', 'flower']
['f', 'i', 'r', 's', 't', 'u']
['b', 'd', 'f', 'h', 'i', 'j']
['apple', 'banana', 'cat', 'deer', 'elephant', 'flower']
['apple', 'banana', 'cat', 'deer', 'elephant', 'flower']

Found this article helpful? You can learn about more Python functions in our learn folder. 

FAQs on The sorted() Function in Python

Q1. Which is more efficient: sort() or sorted() function in Python?

The list function sort() is slightly faster and requires less memory than the built-in sorted() function in Python.

Q2. How do you sort a list in Python?

There are two ways to sort a list in Python: sort() and sorted(). You can use the sort() function to sort lists in sorted order. You can use sorted() to sort strings, tuples, lists, etc. If you don’t know how to use the sort function in Python for lists, you can simply use sorted().

Q3. What is the difference between sorted and sort in Python?

The sort() function just modifies the list it is called on, while the sorted() function needs to create a new list containing a sorted version. Hence, sort() is a bit faster and requires less memory. Also, sort() is just a list method and is only implemented for lists, while sorted() is a built-in function and accepts any iterable.

Q4. How do you sort by a function in Python?

You can sort on the basis of a function by specifying that function as a key in sorted(). Python’s sorted() function sorts any sequence like a list or a tuple. It always returns a sorted list made using the iterable object on the basis of a key without altering the original iterable object. This key refers to the function based on which the list is sorted. 

Q5. Can you sort a list that contains strings and integers both using sorted() in Python?

No, you cannot sort a list that contains both string and numeric values.

Ready to Nail Your Next Coding Interview?

Whether you’re a coding engineer gunning for a software developer or software engineer role, a tech lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!






Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Hosted By
Ryan Valles
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
How you can accelerate your learnings

Recommended Posts

All Posts