Python Tutorial: Sorting Lists, Tuples, and Objects
Skills:
ML Maths Basics60%
Key Takeaways
This video tutorial by Corey Schafer demonstrates how to sort lists, tuples, and objects in Python using the sorted function and the sort method, including custom sorting criteria and key functions.
Full Transcript
hey everybody how's it going in this video we're going to be going over how to sort in Python uh so we're going to look at how we can sort a few different data types so we're going to go over sorting uh lists and tupal you can also run sort on dictionaries and you can also sort objects by a custom criteria um but to get started let's go ahead and look at a couple of ways in which we can just sort a simple list of integers so I have this list here called Li and it contains a bunch of random numbers between 1 and N so if we wanted to sort this how would we do it well I'm going to make a new variable here called sore Li and I'm going to set it equal to and I'm going to run this sorted function and I'm going to pass in our original list to this sorted function so I'm going to save that and then I'm going to go ahead and print this out to the screen so I'm going to uncommon out this print statement here and print out this sorli variable now if I run this you can see here that it did sort this list for us in ascending order so we have 1 through nine here um now let me go ahead and print out my original variable as well so I'm going to print out this Li list and if I print this out now you can see down here that my sorted variable uh is a sorted version of that list but my original is still the uh jumbled unsorted group of numbers now what if I wanted to sort that original uh list of numbers without creating creating a new variable uh well there I can use the sort method on the list so I can say Li do sort and then just close off those parentheses and if I run that now you can see that we have our sorted variable here that is a sorted version of that and also when I ran this li. sort uh it also sorted the original list of integers also now one difference between this sorted function here and this sort method is that the sorted function returns a new sorted list so that's why we can set it to a variable but the sorted method uh just sorts the list in place and then returns none so this can be important because sometimes people get this confused and they'll try to so for example if I was to copy this and I was to try to set this sorli to this li. sort if I was to do that and then run this you can see that instead of getting this sorted list we just get this n value here so if you use the sort method then don't expect a list to be returned because it's just going to go ahead and do that in place okay so now we've seen how we can sort these list in ascending order but what if I wanted these to be in descending order from highest to lowest uh well to do that we can just do pass in this reverse equals true and if I save that and run it now you can see that our new variable here is sorted in descending order order and we can also use this exact same parameter with the sort method so if I pass that in the sort method then it does the uh original variable in place in descending order also okay so why would I want to choose the sort function or the sorted function over the uh sort method well that sort method on the list is uh is fine if you are working with list and if you want to modify it in place but the sorted function gives us a little bit more flexibility because we can pass in any iterable as opposed to uh the sort method which works specifically on lists uh so for example here I have a tuple that has all the same values that we had in our list of integers and the Tuple doesn't have a sort method so if I do a t. sort and run that then we get an error um so what we have to do here is we have to use the sort function so I'm going to do a new variable and do a sorted I'm going to take off this method here since it doesn't have one and I'm going to save that and then I'm going to print out the new variable that we just created here so if I print this out save it and run it now you can see that our sore tup uh variable is a list of the values in our tupal that are now sorted so for another example here I have a dictionary and you can pass a dictionary into sorted also so I'm going to do an sore di equals uh sorted and pass in my dictionary there and then I'm going to go ahead and just print this out to the screen I'm going to comment these out now what sorted will do by default with this dictionary is it's just going to sort the keys so if I run this here then you can see that it returned a list with these sorted Keys here so you can use either method of sorting that you like you can use either the sorted function or the sort method as long as you understand the differences um but for the rest of this video I'm going to use this sorted function because I'm going to be working with examples other than list uh so the sorted function is what you need for that so so far we've sorted integers in ascending and descending order but what if we wanted to sort values based on a different criteria uh so for example what if I had a list of integers here and I wanted to sort these based on their absolute value so you can see I have some uh negative values here now if I was just to print out uh this list right now and run this um actually let me go ahead and sort this list and I'll show you what the uh default sort is for these negative values so I'm going to do sorted and pass in this original list and then I'm going to print out this sorli variable and if I run this you can see that we got uh the exact same thing that it's in right now because these negative values are considered less than the positive values like you'd expect uh so we have -6 54 1 2 3 okay so like I was saying what if I wanted to sort this based on the absolute value of these values so uh it should be 1 2 3 4 5 6 so to do this we can use a key parameter so when our with our sorted here I'm going to pass in a key ke parameter and I'm going to say that the key equals ABS which will use the absolute value function now what this does is it runs each element through this absolute value function before it makes the comparison so now if I run it with this key in place now you can see that my sorted variable is 1 2 3-45 -6 now the key parameter is extremely useful when you're sorting objects with uh named attributes uh so for example here I have this very simple class called employee and within the employee here we just have a name an age and a salary and uh this re method here all it does is it tells python how we want this function represented when it's printed out to the screen so now I have these uh three sample employees here that I've created with uh random names ages and salaries and I'm going to put all three of these employees into a list called employees and now I'm going to try to sort these based on a specific attribute so if I try to sort these without a key then it's not really going to know how to sort them so let me go ahead and try to sort them and print this out to the screen and you can see I get this type error here and it says unorderable unorderable types employee uh can't compare employee to employee so it's getting this employee object here from this list and it's saying hey I don't know how you want me to sort these so we need to use a key to sort these on and I'm going to write a custom function uh in order to sort these so remember our key takes a function that takes each element of our list and Returns what we want to sort on uh so with the absolute value example that I used earlier I was able to use a built-in function for the key uh but for this example we need to write a custom function uh so the function I'm going to write is a very simple one it's just going to be defa and let's see I'll do this eore sort and I'll pass in an employee and then I will just return and we'll uh sort based on the employees name so I'll do empname so now where I ran this sorted function I can pass in this key and I'm just going to pass in I'm going to tell it to do the key as this esort function here so now if I run this then you can see that it returns all of our employees based on their name now if I wanted to sort these based on the employees age then it would be as easy as coming up to this sort function here and instead of returning the employee name I'm going to return the employee age and if I run that now you can see that it's the employee age um in ascending order and lastly if I wanted to do this based on salary then I could go ahead and make this salary and save that and run it and you can see that it sorts it uh by the salary and ascending order now you can also still pass in your other parameters here too so if I did a reverse equals true and then ran this then it would uh sort in the descending order based on our key which is salary so now we have all the salaries and descending order now if you have a complicated sort function then it's probably best to break out uh these functions into separate functions like this but for those of you who are familiar with Lambda functions then you probably notice that something this would be easy to turn into a Lambda function so instead of setting this key equal to this e do sort I really could just do a Lambda here of e now I'm not going to go into lambdas if you haven't seen these before then don't worry about it it's just a way to uh quickly write an anonymous function so if I wanted to sort on the age I'll do or the name I'll do e.name I'm going to go ahead and take out reverse here and save that and run it and now you can see that it is sorted by the employees name in ascending order and since we're using this Lambda function here uh this our sort function up here that we used before isn't actually doing anything so I could still run that without this eore sort function now I should also mention that if you're working with attributes like this that you can import a function that uh specifically does this so I'm just going to do my import from down here um so if I import the operator module and do a from operator import it is called Adder getter this is it right here now what we can do with this is we can just use this as a replacement for our key so and I'm going to take this Lambda out here so I'm going to do an Adder getter and the attribute that I want let's see I'll just do I'll do this as age so if I save that and run it now you can see that it's sorted based on the age so you might wonder why I just didn't show you that Adder getter right away instead of first showing you how to do uh these functions and the lambdas and things like that but knowing how to uh sort with these custom functions it'll allow you to be a little bit more flexible down the road when you want to uh sort more complicated items so I think that about does it for this video I hope it gives you some good ideas for how you can sort your list and objects in any way that you'd like but if you do have any questions just uh feel free to ask in the comment section below uh be sure to subscribe for future videos and thank you all for watching watch
Original Description
In this video we will be learning how to sort lists, tuples, and other objects in Python. We will start by performing simple sorts on a list of integers and then move on to slightly more advanced sorting using custom criteria. Let's get started.
✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms
✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join
✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY
✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot
✅ Corey's Public Amazon Wishlist
http://a.co/inIyro1
✅ Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer
▶️ You Can Find Me On:
My Website - http://coreyms.com/
My Second Channel - https://www.youtube.com/c/coreymschafer
Facebook - https://www.facebook.com/CoreyMSchafer
Twitter - https://twitter.com/CoreyMSchafer
Instagram - https://www.instagram.com/coreymschafer/
#Python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Corey Schafer · Corey Schafer · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Web fonts using CSS Font Face
Corey Schafer
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
Paver Patio Time Lapse
Corey Schafer
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
WordPress Plugins: Imsanity
Corey Schafer
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
Python Tutorial: if __name__ == '__main__'
Corey Schafer
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
Easily Resize Multiple Images Using Picasa
Corey Schafer
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
Git Tutorial: Using the Stash Command
Corey Schafer
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
Git Tutorial: Diff and Merge Tools
Corey Schafer
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
Python Tutorial: str() vs repr()
Corey Schafer
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
Programming Terms: String Interpolation
Corey Schafer
Programming Terms: Idempotence
Corey Schafer
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
Programming Terms: Mutable vs Immutable
Corey Schafer
Python Tutorial: Else Clauses on Loops
Corey Schafer
Overview of Online Learning Resources
Corey Schafer
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
Python Tutorial: Generators - How to use them and the benefits you receive
Corey Schafer
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
Programming Terms: Combinations and Permutations
Corey Schafer
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
Setting up a Python Development Environment in Eclipse
Corey Schafer
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer
More on: ML Maths Basics
View skill →
🎓
Tutor Explanation
DeepCamp AI