Visual Introduction to Python List Comprehensions - Get the same done with less code
Key Takeaways
Daniel Bourke teaches how to use Python list comprehensions to write more efficient code
Full Transcript
all right a rockin pythons were about to code some Python what we've got today is a quick introduction as you might be able to might be able to read a quick introduction to list comprehensions with python and now just a quick reminder there's a blog post it's going to accompany this and a YouTube video you don't need that length that will be below all this code will be available on github in fact all the links I mentioned throughout this video will be available in the description so you can check those out now let's jump in we'll start with why why would you use a list comprehension now the best reason I can give you the one-line version is to get the same thing done in less lines of code now if you have a better version of that leave a comment below and I can update it but at the moment after the research I've done in my use of this comprehensions in the wild and really in the wild I mean just sitting in my desk coding Python has literally been just to just to reduce the number of lines of code now that's good enough that's well and good to say out loud let's see an example now say you were shopping at the math store right because all of us coders we love we love math and we love numbers and we've got a shopping cart here and our shopping cart is it happens to be a list full of numbers now a Python the lesson remember is these square brackets here and we've got about a dozen or so numbers in there so we'll create that and now we've had enough shopping we're gonna go to the cashier and we're gonna start to to hand out our numbers to the cashier one by one now how would you do that with code now first of all we have to create our cashier because they the computer doesn't know that the cashier exists so the cashier starts with zero items and they're going to be an empty list so remember the square brackets and then how would you pass each item one by one we can do that with with a for loop in Python so for item in can't go over each item one by one okay so that's this is our cart here and there these could be our our items yeah that makes sense and then this little little line here we hand the cashier each item and now just a quick reminder if you see anything with a hash in Python usually the words after it is a comment so that means when we run this this little bit of code the words after the hash won't be included so so for item in cart cashier dot append and then in brackets is that item hmm so you can imagine that as with us handing the cashier items so what do you think that will do if we're going through each item one by one right and then appending the cashier you can think of appenders as add add item to to the cashiers list what do you think will happen if we print out cashier we've handed them each item let's let's check it out all right so now cashier has been transformed from that empty empty list and now they have the same as is it the same as cut yeah there's caught up there and cashier all right so we've essentially just gone through our cart which is this this list here and handed the cashier each one so now they have it right but because we've created cashier it also seems like we still have it in our cart right so so they still exist in the car but cashier also has them now tuned this is a this is a this is a Python Python shopping store right so it's not not a real life one we both have the same items now I just realized this might be not the greatest analogy but we'll run with it now how could you do this we've done this in three lines of code how could you do this in unless right so remember that's our Y of using a list comprehension to do the same thing in less lines of code so we've got here cashier two and they're in the Express Checkout Lane they only say say no they're in our - math store and they say no you can't come to me unless you've only got one line of code okay we can do that we're going to use a list comprehension for that now I've written it out here right so let's ever think I've got the square brackets here but we're all doing it on one is this gonna just going to be the same thing we've got car carts up here let's check all right we've created a cashier - surely this can't be the same as the three lines above must check it out if in doubt check it out all right we've got two lists here so the first one is cashier and the second one is cashier - so we go they're exactly the same but what's happening now I've got this is pretty little graphic here right to describe what's going on but if you want the instructions they'll be in the github repo of the code below but I think it's better if we just we just explore this by by talking it out now we've got cashier who's created an empty list right in the non list comprehension and that's in blue and the same step over here is done in the list comprehension in blue all right that looks the same but there's some stuff in the middle of the brackets this time and then we've got for item in car all right that's the same in the green here yeah okay that makes sense but the main difference here is in the red right we've got cashier dot append item but over here we only have the word item hmm what why do you think this is well the main reason you can think about from now is that if the item is in front of the for loop right it negates the reason we're agates and negates the need for having a pent here so what essentially this is putting the item before the for instead of after is that we've pretty much said hey we're gonna do this little part here in one step rather than rather than making it its own line all right let's jump into another example so the third cashier only likes working with even numbers and how could we do that unless we could do it the same above but we might check we might check we might add in a conditional that's our little if statement here adding the conditional to see if the item modulo two equals zero I know what's what's modulo the modulo it's since essentially means remainder is a remainder remainder equals zero so if we divided 20 modulo 2 where as a percentage modulo two what does that equal zero I'd say 20 is an even number what about 4 4 is an even number that makes sense and what about 5 that's going to be one left over right because 5 divided by 2 is is 2 with one left over all right so we'll get rid of that one now cashier 3 equals another empty list we've seen that before then for item in car number we've got out we've still got our card here and we'll check that car yeah that's our car and then if the item this is the the difference here if the item modulo 2 equals zero we're going to append that so what do you think cashier 3 will look like if we got 5 7 9 10 12 15 19 20 which ones will be in cash which ones will we passed a cashier 3 even numbers all right bomb does that make sense we got 10 12 20 22 or not 5 7 9 they're all odd that makes sense now how could we do the same thing right we've got four lines now four lines with a list comprehension are on it so let's check it out we've got cashier 3 equals list create a list with these little square brackets see how in Jupiter at lines makes this one green that one's green and then that one's green too so item for item in cart if item modulo 2 equals equals 0 all right same thing we've got cashier 3 in cashier 3 now what what's happening here again we've got the instructions down below if you want to read them but we're gonna talk through it blue in the non list comprehension we've got cashier 3 equals an empty list here and now we're doing the same thing here now I got green is the same again okay and yellow is the yellow is the same two and now the only difference again is just this little little append item so we've got all components of these four lines but we've put it in one line now can you start to see how how that would help in your Python programs imagine if if this was was maybe another 10 line and you had a fair few of them and then you replace them with this you could start to reduce the amount of code you need to do the same thing now we might do one more one more example and then I'll leave the rest I've put some more challenges in here you can you can check them out for yourself we'll do one more example and then then we'll finish up the video so the fourth cashier only accepts over a hundred numbers over a hundred and odd all right how would you change each of the numbers in car before giving them to cashier for so we've got we've got our shopping cart we want to go to cashier four but they only accept numbers over a hundred end and if they're odd let's let's figure this out remember we've got our cart here let's check that out car five seven yep same car cashier four equals empty list for item in cart we're going to add one hundred to each item all right so because our cashier following the accepts each item so we've got a line there and now then we're going to check if the item modulo two equals equals one and this will this will tell us member if it equals zero it's an even number if it equals one it's an odd number and then we're gonna pass if it fulfills that condition we're going to pass that item to cashier for now let's check out what is cashier for half all right 105 107 109 hundred fifteen are they over a hundred and and are they odd yeah they are and how can you see what it's done it's gone through each item added a hundred and then checked if it's odd yeah that's correct yeah so seven is one hundred and seven nine is a hundred nine ten would be a hundred and ten but that's not an odd number so cashier four doesn't cash she feels like no I only accept over a hundred and odd numbers alright now we're gonna do the same thing with all this comprehension can we cashier four equals remember if we go up here we just have to convert this part into something that looks like this so let's do it line by line let's go we might take this little part out and put it at the start so item plus a hundred for item so now we're up to here for item in cart and we don't need the the semicolon and then we might take this one so we could probably just copy that copy that alright do you think that will work let's check it out print cashier for what have we got wrong for item in cart ah we forgot the in perfect is it the same there we go that's how we can do it right and so now this is another example this one was five one two three four five five lines and we've converted it into one now I've got a few more examples that I've put in here if you want to check out and even a little challenge that's a bit more advanced if you want to try it and if you get stuck on the challenge there's a link to a staff Stack Overflow and then if you now this is only just a brief introduction of what you can do with list comprehensions is far far more things but I just wanted to show you a quick example of some of the powerful powerful things that you can do with list comprehensions in just just one line of code and now if you want something more advanced as an article I'll link it all below but otherwise I'm gonna wrap this tutorial up thank you so much for watching if you have any advice you've spotted any errors leave a leave a comment below or reach out to me somehow any way you want keep rockin pythons [Music]
Original Description
A brief introduction to list comprehensions in Python.
Code on GitHub - http://bit.ly/pythonlistcomprehensioncode
Article version of this video - https://link.medium.com/QfeLxWZ3aU
Advanced list comprehensions - https://www.datacamp.com/community/tutorials/python-list-comprehension
If you have any advice or if there's something you'd like to see in a future video, please let me know.
CONNECT:
Web - http://bit.ly/mrdbourkeweb
Quora - http://bit.ly/mrdbourkequora
Medium - http://bit.ly/mrdbourkemedium
Twitter - http://bit.ly/mrdbourketwitter
LinkedIn - http://bit.ly/mrdbourkelinkedin
Email updates: http://bit.ly/mrdbourkenewsletter
#python #code
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Daniel Bourke · Daniel Bourke · 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
Xbox One S Unboxing and Xbox One Comparison
Daniel Bourke
Text/Profanity Checker in Python
Daniel Bourke
Drawing Flowers in Python
Daniel Bourke
Finding The Right Medium - TDBS 18 April 2017
Daniel Bourke
What Is Neuralink??! - TDBS 22 April 2017
Daniel Bourke
Disagree and Commit, Words of Wisdom from Jeff Bezos - TDBS 19 April 2017
Daniel Bourke
A Lesson In Movement | Raw Training Australia
Daniel Bourke
FALLING IS FUN | Functional Friday 4
Daniel Bourke
My first HACKATHON! | 100 Days of Code 1
Daniel Bourke
MORE MACHINE LEARNING | 100 Days of Code 2
Daniel Bourke
TensorBoard and learning from Einstein | 100 Days of Code 3
Daniel Bourke
Job Interview Tips and Open Ocean Swim | 100 Days of Code 4
Daniel Bourke
I Want To Help 100,000 People Workout | AI Powered Personal Trainer
Daniel Bourke
MACHINE LEARNING IN 5 MINUTES
Daniel Bourke
COFFEE, YOGA and AWS | 100 Days of Code 5
Daniel Bourke
MY FIRST STARTUP WEEKEND | 100 Days of Code 6
Daniel Bourke
GENERATING TV SCRIPTS WITH DEEP LEARNING | 100 Days of Code 7
Daniel Bourke
Attention, please
Daniel Bourke
TEACHING BOTS TO PLAY GAMES | 100 Days of Code 9
Daniel Bourke
Udacity Deep Learning Nanodegree Language Translation Project Submission | 100 Days of Code 10
Daniel Bourke
Learning about Generative Adversarial Networks on Udacity | 100 Days of Code 11
Daniel Bourke
Completing Andrew Ng's Machine Learning Course on Coursera | 100 Days of Code 12
Daniel Bourke
Finishing the Treehouse Python Track | 100 Days of Code 13
Daniel Bourke
GENERATING FACES WITH GANs | 100 Days of Code 14
Daniel Bourke
Graduating From the Udacity Deep Learning Nanodegree | 100 Days of Code 15
Daniel Bourke
WHAT I'VE LEARNED FROM TALKING TO PEOPLE
Daniel Bourke
3 Life Principles I Learned From Ray Dalio
Daniel Bourke
PYTHON && POETRY | 100 Days of Code 16
Daniel Bourke
Physique Update and 6 Things I Wish I Knew Before Starting Gym
Daniel Bourke
The 100 Days is Over! | 100 Days of Code 17
Daniel Bourke
How to Burn Over 100 Calories in 4 Minutes
Daniel Bourke
Solving Sudoku with AI | Learning Intelligence 1
Daniel Bourke
Upper Body Calisthenics Workout in the Park
Daniel Bourke
What is an Adversarial Search Agent? | Learning Intelligence 2
Daniel Bourke
My Self-Created Artificial Intelligence Master's Degree | Learning Intelligence 0
Daniel Bourke
Try Going Over It Again | Learning Intelligence 3
Daniel Bourke
Python and Pullups | Learning Intelligence 4
Daniel Bourke
AI Meets Blockchain! | Learning Intelligence 5
Daniel Bourke
How to Pass the Turing Test + I FAILED | Learning Intelligence 6
Daniel Bourke
Biology and Physics meet Computer Science | Learning Intelligence 7
Daniel Bourke
Udacity Artificial Intelligence Nanodegree Project 3 Progress | Learning Intelligence 8
Daniel Bourke
Passing Project 3 of Udacity's Artificial Intelligence Nanodegree | Learning Intelligence 9
Daniel Bourke
Bayes Networks, Hidden Markov Models and How I Wake Up | Learning Intelligence 10
Daniel Bourke
Udacity AI Nanodegree Progress and Bayes' Rule Explained | Learning Intelligence 11
Daniel Bourke
Udacity AI Nanodegree Project 4 Planning and Progress | Learning Intelligence 12
Daniel Bourke
Finishing Term 1 of Udacity's Artificial Intelligence Nanodegree | Learning Intelligence 13
Daniel Bourke
deeplearning.ai Progress! | Learning Intelligence 14
Daniel Bourke
Coursera Deep Learning Specialization Progress | Learning Intelligence 15
Daniel Bourke
Computer Vision Basics + More deeplearning.ai Progress! | Learning Intelligence 16
Daniel Bourke
My Experience at CodeCamp, Intro to Keras and Failing Hard | Learning Intelligence 17
Daniel Bourke
In-Depth Udacity Deep Learning Nanodegree Review
Daniel Bourke
Completing the Deeplearning.ai Specialization on Coursera | Learning Intelligence 18
Daniel Bourke
You're Never Too Young to Start Learning AI - Learning Intelligence Talks with Shaik Asad
Daniel Bourke
Starting Term 2 of the Udacity Artificial Intelligence Nanodegree | Learning Intelligence 19
Daniel Bourke
Submitting the Computer Vision Capstone Project | Udacity AI Nanodegree | Learning Intelligence 20
Daniel Bourke
Leg Day at World Gym Northlakes ft. Ben Jones Fitness
Daniel Bourke
deeplearning.ai Sequence Models Course Progress | Learning Intelligence 21
Daniel Bourke
Graduating from the deeplearning.ai Coursera Specialization | Learning Intelligence 22
Daniel Bourke
Udacity Artificial Intelligence Nanodegree NLP Concentration Progress | Learning Intelligence 23
Daniel Bourke
Learning How to Build What's Next at Google Cloud On Board Brisbane
Daniel Bourke
Related Reads
📰
📰
📰
📰
I Spent My Career Making People Unnecessary — Years Later, It Came for My Own Child
Medium · AI
AI Finds an Eternal Creator More Plausible Than the Universe Being a Simulation (Or Being a…
Medium · AI
10 Jobs That Are Safe Because Robots Cost Too Much
Forbes Innovation
Five Signals From the Frontier of AI Research
Medium · AI
🎓
Tutor Explanation
DeepCamp AI