Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

The sorted() Function in Python

Last updated by Vartika Rai on Sep 25, 2024 at 11:02 PM | Reading time: 5 minutes

The fast well prepared banner

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

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

The sorted() Function in Python
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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!






Last updated on: 
October 10, 2024
Author

Vartika Rai

Product Manager at Interview Kickstart | Ex-Microsoft | IIIT Hyderabad | ML/Data Science Enthusiast. Working with industry experts to help working professionals successfully prepare and ace interviews at FAANG+ and top tech companies

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

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

The sorted() Function in Python

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

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