Python Tutorial: Comprehensions - How they work and why you should be using them

Corey Schafer · Beginner ·🛠️ AI Tools & Apps ·10y ago

Key Takeaways

This video tutorial by Corey Schafer covers the basics of Python comprehensions, including list, dictionary, and set comprehensions, and how they can be used to replace map, filter, and for loops to improve code readability and simplicity. The tutorial provides examples and code snippets to demonstrate the usage of comprehensions in various scenarios, including nested loops and conditions, and generator expressions.

Full Transcript

hey everybody how's it going in this video we're going to be taking a look at list comprehensions in Python so basically a list comprehension is an easier and more readable way to create a list now I think the best way to learn list comprehensions is to first show what it would look like in a for Loop because I think um everybody is familiar with for loops and even if you're coming from another language uh you'll be familiar with that as well so let's take a look at some of these examples and I'll show you some of the advantages to list comprehensions in terms of uh how easy they are to write and also in how easy they are to read so let's go ahead and take a look at this first example here so in this first example I have this comment here that this is just going to be the easiest Loop all it does is pretty much copy it so I'm saying that I want in for each in in nums so if you to write this in a for Loop first you would create an empty list and then you see here I have a list of numbers 1 through 10 and then I have this empty list my nums so we're doing four in in nums so it's going to Loop through all these numbers my list. append in so it's just going to add each number to this list then we're going to print out that list so let's go ahead and run that and you can see that it's exactly what we'd expect it's just a copy of the top list here now let's see what this looks like in a list comprehension and also notice how similar the list comprehension is to my comment here so what I'm going to say is I'm going to make my list equal to and then brackets so the brackets means that we're making a list and then let's try to pretty much copy exactly what is in the comment here so I want in and then for each in in nums that's a list comprehension so what so this is what we're returning this is what we want I want in and then this is the for Loop here for in and nums so if I save that and run it then I actually have to print this out so that it shows up so we'll run that and you'll see that it's the exact same result that we had from the for Loop but this is much easier to write and it's pretty easy to understand also so that's about the easiest list comprehension that you can do um so let's do a slightly more complicated example so in this example here if we read the comment I'm saying that I want n s so n * n for each n in nums so this is pretty similar to our previous example but now we're actually returning the square of n instead of just copying all the values so to do this in a for Loop we would create an empty list and then we would Loop through all the numbers and then we would append the square to the list and and then when we're done we can print the list so if I run this code then you can see that our result we get all of the squares of each number in this 1 through 10 list okay now let's see the same example but in a list comprehension and also um let's notice how similar it is to the comment again so it's almost like reading exactly what we want so we want n * n for n in nums so this is what we are appending to our list and this is the for Loop here so if I save that and then let me remember to print it out this time and then run it then we get the exact same result as our for Loop now there's another way to do something like this that's very similar if you know how to use maps and lambdas then maybe you've made something like this before so let me comment out this code so map pretty much runs everything in the list through a certain function and Lambda is an anonymous function so if I save this and print it out you can see that we got the same result but list comprehensions pretty much do away with these map functions because they're no longer needed this works and it's a oneliner just like the comprehension but you can't read this and understand exactly what it's doing unless you already knew about these to begin with if you compare this readability to the list comprehension somebody who's completely new to python can see this and say n * n for n and nums and that just is readable it just kind of flows together and you can kind of understand what's going on with these maps and lambdas it says map Lambda n n times n nums it just doesn't it just doesn't read very well and you have to be experienced with those before you understand what's going on so if you are using maps and lambdas from within your code then you might want to check and see if those can be converted to list comprehensions because 99% of the time they can be so I'm going to comment these out here and erase these and we'll move on to um a slightly more difficult example okay so in the comment for this example I'm saying that I want n for each n in nums if n is even so this is going to create a list that is all the even numbers of our original 1 through 10 list so what's going on in our for Loop here is we're creating our empty list and then we're saying for each item in the numbers list then if that number mod two which uh will give us the remainder after we divide it by two is equal to zero that means that it's even so then a pin that to our list and then at the end we'll print out print out our list so if we run that then you can see that it works we get 2 4 6 8 10 so now let's look at this same example using a list comprehension so I'm going to say my list equal to brackets which means that we're making a list so we want in for n in nums if in mod 2 equals equals zero so what we're saying is that we want we want an item for each item in nums if that item mod 2 equals equal zero so let's save that and actually let me print it out here and then run that and you can see that we get the exact same result as our for Loop now just like the map and Lambda functions there's also the filter and Lambda functions which is pretty much the same thing so instead of map we have filter and what this does is it filters um it runs the list through this function and only gives us the values that are uh even so if we print this out you can see that it works but the same with the map Lambda function people just aren't going to know what this is if they're new to it it's just not as readable as this list comprehension is so let's go ahead and delete all of this stuff and move on to a slightly more difficult example so in this example here I'm saying that I want a letter number pair for each letter in AB C D and each number in 01 2 3 so for example I would want a0 A1 A2 A3 b0 B1 1 B2 B3 and so on so if we were to do this with a for Loop then we would create our empty list then we would do a for Loop for letter in ABC and then within that for loop we're going to have another nested for Loop and say for Num in range four which will give us 0 one 2 3 and then we're going to do a my list. ainn a tuple of the pair letter and number so if I save that and I run it then you can see that we got all of our pairs we got a z A1 A2 A3 b0 B1 B2 B3 and so on so we can have these nested for Loops in list comprehensions as well so if I was to do this in a list comprehension I would say my list equals create an empty list Here and Now what I want is I want letter num for letter in a b c d and then write after that for Loop for Num in range four so let's save this and print it out and make sure I typed everything right so we print that out and we see that we get the exact same result as our for Loop now let's walk through this one one more time so what we're saying is that that we want a list so we open up our brackets and we're saying that we want this tupal letter number four letter in ABC D for Num in range four so one thing I probably should have mentioned earlier is that these values that we're saying that we want they have to match these values that we assign here so I couldn't just call this number here I couldn't say that I want letter num for letter in ABCD four number in range four because it's not going to know what this value is this numb value we have to use the same values that we want uh whenever we say that we want those values in the list so you can see how we can start to do some complicated lists here um that take you know uh a good bit of lines of code that we can write as a oneliner and it's slightly more readable as well but it's not only list that you can do these comprehensions with you can also do this with dictionaries and sets also so if I delete that then let's move down to our next example here now this is going to be an example of a dictionary comprehension so I have two lists here I have names and then I have uh their superhero name that matches up with their first name so um if you've never seen this ZIP function here let me just print out this ZIP function here so that you know what it does so what the zip function does is um so all these match up one to one so the first index of names is uh matches up with the first index of the heroes list here now if we run zip then it's going to create a list of tupal that match those up for us so it's going to say it's going to be a tupal of Bruce Batman and then the next tup will be Clark Superman and so on so I'm going to make a dictionary comp renson using this uh ZIP function so let me take that out and now you can see that in my comment here I'm saying that I want a dictionary of the name as the key hero as the value for each name hero in zip names and heroes and this is going to be a list of tupal so here in the for loop I am making an empty dictionary and then I I'm looping through these tupal and saying that for the name of that tupal I want to be my key in the dictionary and for the hero of that tupal I want to be the value in the dictionary and then I'll print out the dictionary here so if I save that and run it then you can see that we get our dictionary using our for Loop so now let's say that we want to do this as a list or as a dictionary comprehension so I'm going to do my dict equal to now instead of the brackets this isn't a list anymore it's a dictionary so we're going to use these braces instead so for the dictionary comprehension I'm going to say name and then colon hero for name comma hero in zip heroes or actually that's going to be names comma Heroes so save that and now let's print this out and you can see that we get the exact same result that we did with our for Loop and it's easy to add restrictions onto the ends of these comprehensions so like in this comment here uh I want to do the same thing but I don't want Peter added to this list so here at the end I can just say if name is not equal to Peter and then run that and you can see that we get our list uh without Peter and Spider-Man included in the list so comprehensions really make it easy to add those loops and those conditionals onto uh the existing comprehension so now let's go ahead and delete the dictionary comprehension example and we'll move on to the set comprehensions so if you don't know what a set is a set is pretty much like a list except it has all unique values so uh you see here that we have this jumbled mess of a bunch of values between one and or between 0o and 10 and um so whenever we make a set and loop through and add those values to the set the final set is going to have all unique values so if I have this list of nums uh to do this in a for Loop I'm going to say my set equal to an empty set and then for each item in nums my set. add that item and now I'm going to print out my set so let's save that and run it and you can see that I get all the unique values um from that nums list so now if I wanted to turn this into a set comprehension then I can comment out the for Loop there and I'm just going to say my set equal to and this is going to be braces again just like the dictionary comprehension but we're not going to have a colon like the dictionary comprehension had so now we can do this just like the other list comprehensions so we want n for n in nums so save that now this is doing exactly what this for Loop did it's just adding in for each number in the nums list so if I print this out and run it then you can see that we get the exact same result that we got with the for Loop and just like with the list comprehensions you can add nested loops and condition onto the end of this as much as you want um so let's go ahead and delete that and so that does it for the comprehensions now I do have this one last example here of generator Expressions now generators are a lot different than lists and dictionaries and sets um but I wanted to include them in this tutorial because uh a generator expression is so similar to a list comprehension so if you do want a more in-depth look at the advantages of generators then you can watch my video that I made uh specifically on generators but in this example I'm just going to focus on generator Expressions okay so if we uncomment out this code here this is just a regular generator this isn't an expression so if we look at the comment I'm saying that I want to yield n * n so the square of n for each in and nums just like our other examples so here our generator function uh we we are passing in this nums list and then we're saying for n in nums yield the square of N and then here we're saying my gen equals this gen function and we're passing in that list of numbers and then finally here at the bottom we are looping through that generator and printing out each I so let's save that and run it and you can see that it uh ran the for Loop and printed out all of the values in that generator now if I was to do this with a generator expression uh the syntax is almost identical to a list comprehension but instead of the brackets or the braces we're going to use parentheses so now just like the other examples we can say I want n * n for n in nums save that and then we still need to keep our for Loop here because we have to iterate through that generator so if I save that and print it out then you can see that we got the exact same result as we did with these uh lines of code that where we had to create the generator function and do the for Loop and then create the generator using the function and all of that so you can see how this one line of code is not only a lot easier to write and maintain but it's also a lot more readable as well as well so that about does it for this video on list comprehensions um you you'll be surprised at how often you'll use these and how much code that you can go through your code base and replace these long nested for loops with these list comprehensions so if you guys do have any questions just ask in the comment section below be sure to subscribe for future python videos and thank you guys for watching

Original Description

Python comprehensions are a very natural and easy way to create lists, dicts, and sets. They are also a great alternative to using maps and filters within python. If you are using maps, filters, or for loops to create your lists, then most likely you could and should be using comprehensions instead. In this video, we will look at how comprehensions work, why you should be using them, and the benefits they have over the alternatives. The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/List_Comp ✅ 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 · 47 of 60

1 Web fonts using CSS Font Face
Web fonts using CSS Font Face
Corey Schafer
2 Using Font Awesome in Desktop Applications (OS X)
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
3 Sublime Text 2: Setup, Package Control, and Settings
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
4 ArcGIS API for JavaScript Part 1: Our First Web Map
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
5 Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
6 Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
7 ArcGIS API for JavaScript Part 2: Starting Templates
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
8 Paver Patio Time Lapse
Paver Patio Time Lapse
Corey Schafer
9 Mac Tip: Ways to perform Screen Capturing and Screenshots
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
10 WordPress Plugins: Imsanity
WordPress Plugins: Imsanity
Corey Schafer
11 WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
12 Sublime Text 3: Setup, Package Control, and Settings
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
13 Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
14 Mac Tip: Adding Folder Stacks to the Dock
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
15 CSS Tips and Tricks: Add External URLs to Print Stylesheets
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
16 JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
17 JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
18 JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
19 JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
20 JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
21 JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
22 JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
23 Python Tutorial: if __name__ == '__main__'
Python Tutorial: if __name__ == '__main__'
Corey Schafer
24 Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
25 How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
26 Easily Resize Multiple Images Using Picasa
Easily Resize Multiple Images Using Picasa
Corey Schafer
27 Easily Resize Multiple Images Using the Mac Terminal
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
28 Python Tutorial: virtualenv and why you should use virtual environments
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
29 Python Tutorial: pip - An in-depth look at the package management system
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
30 Git Tutorial: Using the Stash Command
Git Tutorial: Using the Stash Command
Corey Schafer
31 How Software Engineers, Developers, and Designers can volunteer their skills
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
32 Git Tutorial: Diff and Merge Tools
Git Tutorial: Diff and Merge Tools
Corey Schafer
33 Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
34 Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
35 Python Tutorial: str() vs repr()
Python Tutorial: str() vs repr()
Corey Schafer
36 Programming Terms: DRY (Don't Repeat Yourself)
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
37 Programming Terms: String Interpolation
Programming Terms: String Interpolation
Corey Schafer
38 Programming Terms: Idempotence
Programming Terms: Idempotence
Corey Schafer
39 Python Tutorial: Namedtuple - When and why should you use namedtuples?
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
40 Programming Terms: Mutable vs Immutable
Programming Terms: Mutable vs Immutable
Corey Schafer
41 Python Tutorial: Else Clauses on Loops
Python Tutorial: Else Clauses on Loops
Corey Schafer
42 Overview of Online Learning Resources
Overview of Online Learning Resources
Corey Schafer
43 Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
44 Git Tutorial for Beginners: Command-Line Fundamentals
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
45 Quickest and Easiest Way to Run a Local Web-Server
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
46 Python Tutorial: Generators - How to use them and the benefits you receive
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
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
48 Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
49 Programming Terms: Combinations and Permutations
Programming Terms: Combinations and Permutations
Corey Schafer
50 Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
51 Preparing for a Python Interview: 10 Things You Should Know
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
52 SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
53 SQL Tutorial for Beginners 2: Creating Your First Table
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
54 SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
55 Linux/Mac Terminal Tutorial: Navigating your Filesystem
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
56 Python: Ex Machina Easter Egg - Hidden Message within the Code
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
57 Mac Tip: New Split Screen Feature in El Capitan
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
58 Setting up a Python Development Environment in Eclipse
Setting up a Python Development Environment in Eclipse
Corey Schafer
59 Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
60 SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer

This video tutorial covers the basics of Python comprehensions and how they can be used to improve code readability and simplicity. It provides examples and code snippets to demonstrate the usage of comprehensions in various scenarios.

Key Takeaways
  1. Create an empty list
  2. Loop through a list of numbers
  3. Append numbers to a list
  4. Print a list
  5. Create a list comprehension
  6. Use a for loop to iterate over a list
  7. Use a nested for loop to iterate over multiple lists
  8. Use list comprehensions to create lists of even numbers, letter-number pairs, and other data structures
  9. Create a dictionary comprehension to generate a dictionary from a list of tuples
  10. Create a set comprehension to generate a set with unique values
💡 List comprehensions can be used to replace map, filter, and for loops to improve code readability and simplicity.

Related AI Lessons

Up next
AI in Care - Katie Furey, Pairly.com
The Access Group
Watch →