10 Python Comprehensions You SHOULD Be Using

  Рет қаралды 81,591

Tech With Tim

Tech With Tim

Күн бұрын

In this video, I will be showing you 10 Python comprehensions you can & should be using. These comprehensions will progress in difficulty, so be sure to stick around until the end of the video!
If you want to land a developer job: techwithtim.net/dev
Skool community for free resources: www.skool.com/software-develo...
Discord server: / discord
🎞 Video Resources 🎞
⏳ Timestamps ⏳
00:00 | Overview
00:11 | Basic List Comprehensions
02:06 | Comprehension Condition
04:22 | If You're Serious About Becoming A Developer
05:20 | Comprehension With Multiple Conditions
07:42 | Multiple List Comprehension
09:18 | If/Else In A Comprehension
11:22 | Nested List Comprehension
14:32 | Transformation In Comprehension
15:38 | Dictionary Comprehension
16:47 | Set Comprehension
17:49 | Generator Comprehension
Hashtags
#techwithtim
#programming
#python

Пікірлер: 110
@TechWithTim
@TechWithTim Ай бұрын
If you like this style of teaching check out my full software development program: techwithtim.net/dev
@DarinCox-or1iq
@DarinCox-or1iq Ай бұрын
Job opportunity 🙌 🙏 is the money you have given to many of these people and I will send them some more important information about what you have done ✔️
@satheshasachithra
@satheshasachithra Ай бұрын
could you do javascript beginner to pro challenges on code wars or anyotherway
@MiAmigoKier
@MiAmigoKier Ай бұрын
May I ask, what is your keyboard, it sounds great btw
@DarinCox-or1iq
@DarinCox-or1iq Ай бұрын
Ok
@kerrykreiter445
@kerrykreiter445 Ай бұрын
Absolutely the best tutorial I’ve watched on comprehensions. Thank you for making it very understandable. I would also appreciate the same type of video covering Lambda functions. Thanks again for helping so many!!
@mikec64
@mikec64 Ай бұрын
I found the way you formatted the comprehension that calculates squares is a really helpful way to think about comprehensions, even if I compress them to a single line. In that form, it looks like the comprehension just skips the result=[ ] statement, which I always thought was ugly. And in nested loops it gets rid of all those intermediate lists and variables. For the first time they look more elegant to me.
@lucasseagull8282
@lucasseagull8282 Ай бұрын
Man, you grew a lot in past 3 years :)) I'm just watching your video called: Python Selenium Tutorial #2 - Locating Elements From HTML, where you are referring to your website for testing. However, it's no use as the website is now different - can you do the remake of your selenium tutorials / make it up-to date? Thank you and good luck!
@user-ty1gv6xg1o
@user-ty1gv6xg1o 14 күн бұрын
Man... I love how clean this looks
@eladiomendez8226
@eladiomendez8226 Ай бұрын
Is this list comprehensive of all comprehensions ? 😅
@gaussdog
@gaussdog 27 күн бұрын
Is your comprehension comprehensive?
@YarPirates-vy7iv
@YarPirates-vy7iv 17 күн бұрын
As a connoisseur of dad jokes I want to thank you for this contribution. 🎉
@NearLWatson
@NearLWatson 5 күн бұрын
Comprehensive list of comprehensions to help comprehend a list of comprehensions within which the list comprehension is included.
@Soyosan22
@Soyosan22 Ай бұрын
This is an absolutely excellent video. Your examples and explanations are always great. I think it is time for you to start working on a Python book. I am sure it will be a huge success. :)
@kapibara2440
@kapibara2440 26 күн бұрын
Great content, like always from you. Thanks Tim! Greetings from Poland 😊
@swagatopablo
@swagatopablo 26 күн бұрын
Most comprehensions can be replaced by some combination of map and filter, which I find far cleaner. Further, in most cases, you will iterate through the iterator only once, in which case, you can leave it as an iterator (map and filter) form until you use it (unlike, for example, using comprehension to give you an iterable). This is far more pythonic and memory efficient too.
@elatedbento
@elatedbento 19 күн бұрын
Things are a bit gray here. You can easily replace the list comprehension to a generator comprehension by just changing to parenthesis, in case you need that memory efficiency. Most developers nowadays advocate for list/gen comprehensions over map and filter statements, for readability and performance. There is nothing wrong with map and filter, though.
@swagatopablo
@swagatopablo 18 күн бұрын
@@elatedbento Curious, do most developers advocate against map and filter? Why? I am just curious if there have been some benchmarking on performance or some other motivation behind it that I don't know of. In general, I love the clarity of functional constructs which explains my bias.
@sdmagic
@sdmagic Ай бұрын
Very well done. Thanks!
@Ohiostategenerationx
@Ohiostategenerationx Ай бұрын
Looks good. I'm just now learning it but as far as I can tell it looks way better than the original code.
@i5presnt562
@i5presnt562 22 күн бұрын
I needed this kind of videos thx so much
@ricdelmar4961
@ricdelmar4961 Ай бұрын
Another interesting point about generator expressions, is how they work with the all and any functions. Those functions will use the same kind of short-circuit evaluation that compound conditionals use -- that is, they will only evaluate as many items from the generator that they need in order to determine whether the result should be True or False.
@BruceDuncan
@BruceDuncan 25 күн бұрын
Oof you got me. Been writing python for 15 years and never knew that you could have multiple `if` statements in a comprehension. I have always written `and` and assumed you made a syntax error 😂
@wandksitesupport2777
@wandksitesupport2777 16 күн бұрын
nah jit bro got a whole level of python knowledge but still dont know that
@nirty6340
@nirty6340 14 күн бұрын
​​@@wandksitesupport2777 it doesnt matter to be honest correct me if i wrong but if you replace all if's with and expect first it would work the same
@AlexTrusk91
@AlexTrusk91 Ай бұрын
Thanks, pretty edutaining stuff
@DrDeuteron
@DrDeuteron Ай бұрын
Nested list comp: >>>flattened = list(chain(*matrix)) chain is from itertools.
@jamesarthurkimbell
@jamesarthurkimbell Ай бұрын
They also have a chain_from_iterable for this case... but I agree, I'd rather just type the star
@andresbonelli
@andresbonelli Ай бұрын
You can even nest comprehensions inside of other functions, inside of user inputs... ie: print(*(list("Hello" for _ in range(int(input("How many 'Hello' would you like to print? ")))))) Python is wild...
@user-ts9ks8in2n
@user-ts9ks8in2n Ай бұрын
Comprendre! Thanks Tim.
@shapunna6151
@shapunna6151 7 күн бұрын
Thanks a lot ❤
@krzysiekkrzysiek9059
@krzysiekkrzysiek9059 25 күн бұрын
And these are the best kind of tips 👌
@yasufadhili
@yasufadhili Ай бұрын
Thanks alot again
@Indently
@Indently Ай бұрын
07:28 I actually never knew you could insert multiple conditions like that, pretty cool!
@BrianStDenis-pj1tq
@BrianStDenis-pj1tq Ай бұрын
Great video. One thing you might add is a speed comparison. I believe comprehensions are extremely fast, and while one might argue readability, performance is far superior.
@GigasAhriman
@GigasAhriman Ай бұрын
I've always wondered about speed comparison but I have no idea how to set that one up
@BrianStDenis-pj1tq
@BrianStDenis-pj1tq Ай бұрын
@@GigasAhriman The last example in this video showed a scenario. Star with a range of like 100M. Then make a list of the integers. Do it in a for loop (with list.append()) and then in a comprehension. Use time.perfcounter() before and after.
@GigasAhriman
@GigasAhriman Ай бұрын
@@BrianStDenis-pj1tq that's the first time I've heard of time.perfcounter() Ty
@BrianStDenis-pj1tq
@BrianStDenis-pj1tq Ай бұрын
@@GigasAhriman BTW, I left out a character, its time.perf_counter()
@mikec64
@mikec64 Ай бұрын
@@BrianStDenis-pj1tq Thanks for the perf_counter tip. I ran the 3D array (1000 x 200 x 500) test both ways. The loop was 4.7 sec, the comprehension was 2.6 sec. Results varied if I used numbers too small or so large that they ate up all my RAM.
@largewallofbeans9812
@largewallofbeans9812 2 күн бұрын
For number 1, it’s much easier just to write list(range(10)) or [*range(10]. Of course, this doesn’t allow for manipulation of the numbers in the range, but it’s still something to be aware of. Same type of thing goes for the conditional comprehension and the filter function.
@AirLight1646
@AirLight1646 10 күн бұрын
What a comprehensive guide.
@KeithKazamaFlick
@KeithKazamaFlick Ай бұрын
my guy tim. cheers buddy
@adiaphoros6842
@adiaphoros6842 Күн бұрын
The nested list comprehension would be more readable to me if the syntax goes inside out. For example: flattened = [num for num in row in array]
@andiglazkov4915
@andiglazkov4915 Ай бұрын
Thanks 😊
@stefanvanbraam4378
@stefanvanbraam4378 21 күн бұрын
Hi. Great video. Do you have a video that teaches you how to change the text color (scope) such as print, for, if statements in Sublime 3? Thanks
@user-qs2hn9zp3d
@user-qs2hn9zp3d Ай бұрын
tq bro.. I have learned lot. 🥺🥺
@TechWithTim
@TechWithTim Ай бұрын
Welcome 😊
@Da_phuc
@Da_phuc Ай бұрын
Ah yeah!! Good stuff aahhhhhhhhh!! More baby boi !!!
@jackiesofir4660
@jackiesofir4660 Ай бұрын
This is the only way we populated list where I work. Literly appending is I'll advised
@godwinv4838
@godwinv4838 Ай бұрын
thank you
@jamesarthurkimbell
@jamesarthurkimbell Ай бұрын
Another benefit is that variables don't leak out the way they do with for loops. Less of an issue if you're using underscores, but still.
@dmaynor
@dmaynor 27 күн бұрын
How does the example at &t6:30 work? you don't have to terminate login in []?
@DrDeuteron
@DrDeuteron Ай бұрын
regarding the check on string length (5:40): string[slice(None, 1)] == 'a' and string[slice(None, -2, -1)] == 'y' works so: >>>valid_string = list(filter(lambda string: string[slice(None, 1)] == 'a' and string[slice(None, -2, -1)] == 'y', options)) takes care of business, buy may necessitate a code comment.
@chinzorigyou
@chinzorigyou Ай бұрын
Thanks
@tincustefanlucian7495
@tincustefanlucian7495 20 күн бұрын
nice synthesis. I'm using all of them(except multiple if condition, nice one). I would add another dictionary comprehension that I use often, when i want to filter items or find items in a really big dictionary: hay_dictionary = {"first": 1, "second": 2, "needle":4, "second_needle": 5, "last": 6, .................} a really big dictionary {k:v for k, v in hay_dictionary.items() if "needle" in k} this will return only the item that have in key "needle" {"needle":4, "second_needle": 5}
@YOURMOTIVATOR-km2gy
@YOURMOTIVATOR-km2gy Ай бұрын
Big fan man
@shawn445
@shawn445 Ай бұрын
This is a great video but I've been having the issue of figuring out when I would use these in real life scenarios m it would be great if I had applicable examples
@ToxoYoutube
@ToxoYoutube Ай бұрын
Hey tim, i was wondering if you had any videos on your channel that could help me with DSA in python. Do you have like a youtube playlist?
@kazmi401
@kazmi401 Ай бұрын
The have a paid course on algoexpert. But that's not for beginners. i have a year of experience. even that's was a little bit hard for me. but now i am smooth. mmmm it was great "i think".
@nascentnaga
@nascentnaga Ай бұрын
I did not know sum() would store the internal value. That is very interesting.
@mahmoudhasan6954
@mahmoudhasan6954 Ай бұрын
You can apply sum(),max(),min(), len() and other functions as well
@justliberty4072
@justliberty4072 12 күн бұрын
I'm surprised that Tim didn't mention the time-performance benefits of using comprehensions.
@AnatoliyRU
@AnatoliyRU 18 күн бұрын
for first `values = list(range(10))` is better
@elatedbento
@elatedbento 19 күн бұрын
Comprehension with multiple conditions
@TragicGFuel
@TragicGFuel 14 күн бұрын
Yeah personally, these comprehensions would confuse the hell out of someone who's unfamiliar and probably would have understood the more verbose syntax easier.
@CynicAtLarge
@CynicAtLarge Ай бұрын
3D example would be more clear if you used different range values for each dimension.
@TechWithTim
@TechWithTim Ай бұрын
Good point that was not the best example
@svdden_strike
@svdden_strike Ай бұрын
Can you teach us how to create a CMS for a website
@gogasaldadze1639
@gogasaldadze1639 20 күн бұрын
i would prefer to use this type lis=[i for i in a if i[0]=='a' and i[-1]=='y']
@giovannisins
@giovannisins Ай бұрын
Shouldn't at 5:59 the first condition be greater than or equals to 2 like you show after?
@HarnessedGnat
@HarnessedGnat 17 күн бұрын
In the first group the unwanted options are being filtered out, (toss out anything too short), and in the comprehension he is selecting for those strings that match the requirements. Same end result but one test is the inverse.
@giovannisins
@giovannisins 17 күн бұрын
You are right, thank you
@DrDeuteron
@DrDeuteron Ай бұрын
even/odd. since if is the new goto (harmful), I select with: {0: 'even', 1: 'odd'}[x % 2] which is why devs hate me. Actually, I'd map the list to (2).__rmod__ and map that to dict.getitem.
@ImmacHn
@ImmacHn 5 күн бұрын
So basically, sintactic sugar for reduce/map , got it.
@erikjohnson9112
@erikjohnson9112 25 күн бұрын
I don't get a generator for your last example: >>> sub_of_squares = sum(x**2 for x in range(100)) >>> type(sub_of_squares)
@JanKowalski-dm5vr
@JanKowalski-dm5vr 24 күн бұрын
This is generator: sub_of_squares = (x**2 for x in range(100)) and you can use next(sub_of_squares) And this is sum function that call generator instead create whole list sub_of_squares = sum(x**2 for x in range(100))
@garrettsmith315
@garrettsmith315 Ай бұрын
A little heavy on the reverb, could use a tiny bit of bass boost to the voice as well.
@TechWithTim
@TechWithTim Ай бұрын
Agree unfortunately my recording setup isn’t the best right now as I’m moving around
@garrettsmith315
@garrettsmith315 Ай бұрын
@@TechWithTim Great content thought...waiting for some Golang.....
@lesheq85
@lesheq85 18 күн бұрын
why in 17:42 you got 16 on the first spot and the rest in order? I don't think that was supposed to happen
@kazmi401
@kazmi401 Ай бұрын
Keyboard name please.
@mikeeotool2677
@mikeeotool2677 Ай бұрын
TIIIIMMMMM i copy the the script "strings that start with 'a" and end with "y" as it shows in the screen and when i run it give me 3 errors for every instance that you have "string" and asked me for "strings" and the code runned great, so I think you made 3 typos.
@jayamankrah4328
@jayamankrah4328 Ай бұрын
Check from your side, it might be you made the typo.
@BiologyIsHot
@BiologyIsHot 12 күн бұрын
The syntax for flattening a list always feels very wrong. Given that single list comprehensions put their iterable to the left, it always feels odd that for num in row is to the right of matrix. It REALLY feels like it should have been [num for num in row for row in matrix] instead of what it actually is. I actually think this is one of the worst bits of Python and I encourage people to not do these neste/unpacking list comphrensions because of how unreadable they are. It would have been great if they gave us some kind of unpacking operator syntactic sugar here with [*row for row in matrix]. That would have been a much better syntax than [item for sublist in nested_list for item in sublist]
@JosephKH.77
@JosephKH.77 Ай бұрын
Should i watch harvards cs50 online?
@AlexTrusk91
@AlexTrusk91 Ай бұрын
yes, worst case would be entertainment & understanding concepts>hard facts. And why shouldn't you just go for it, it's free of charge
@lamborghinicentenario2497
@lamborghinicentenario2497 Ай бұрын
Didn't even know this wizardry existed
@Sanjay-tiwary
@Sanjay-tiwary Ай бұрын
Hi
@CryptoBuilders
@CryptoBuilders Ай бұрын
is this pythonic?
@wandksitesupport2777
@wandksitesupport2777 16 күн бұрын
i like to watch your video especially in coursecareer im trying to get a job with software engeneer
@newh1ve39
@newh1ve39 Ай бұрын
I understand the intention… but I dont understand why you dont show the differences in execution time. If there is no difference its not worth it at the moment in my opinion.
@HarnessedGnat
@HarnessedGnat 17 күн бұрын
It’s been pointed out in other comments that comprehensions are faster…. Someone suggested Time.perf_counter() Programmers reading code efficiently (see what’s written, faster and more reliably) has value too.
@LiamInviteMelonTee
@LiamInviteMelonTee 12 күн бұрын
I guess this is mostly about readability, the performance increase varies from version to version of python (just got a boost in 3.12, see mcoding's video)
@timothytjerije7262
@timothytjerije7262 Ай бұрын
Good day Tim. Your text is not visible, please find a way. Your lessons are good though...
@TechWithTim
@TechWithTim Ай бұрын
Hmmm turn up your resolution
@jeromemoutou9744
@jeromemoutou9744 28 күн бұрын
​@@TechWithTim the red text is quite hard to see, especially when highlighted.
@BoredBoy888
@BoredBoy888 24 күн бұрын
Text is perfectly fine, just find a way to read it 😉
@HarnessedGnat
@HarnessedGnat 17 күн бұрын
All text colors look fine on this tablet. Adjust monitor, or try a different one.
@MW-cs8zd
@MW-cs8zd Ай бұрын
Turn that frown upside down
@HarnessedGnat
@HarnessedGnat 17 күн бұрын
Hi Tim, I would enjoy watching just as much without the orange jiggy transitions… not needed IMO. (Overstimulated) Tx!
@HarnessedGnat
@HarnessedGnat 17 күн бұрын
After posting that I also noticed that because we are learning to read code (as well) we’re watching REALLY closely…
@rudiklein
@rudiklein 6 күн бұрын
I preferred the more verbose code until I saw this video.
@RebelinhoKZ
@RebelinhoKZ Ай бұрын
chatGPT just killed all these tutorial videos....
@chrisw1462
@chrisw1462 Ай бұрын
You're doing something as complicated as Comprehensions, but you use multiple If's instead of Boolean operators??? ROFL
Python Generators Explained
28:37
Tech With Tim
Рет қаралды 139 М.
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 77 М.
10 Minutes To Escape Or This Room Explodes!
10:00
MrBeast
Рет қаралды 64 МЛН
Mac & Cheese Donut @patrickzeinali @ChefRush
00:53
albert_cancook
Рет қаралды 226 МЛН
How Senior Programmers ACTUALLY Write Code
13:37
Healthy Software Developer
Рет қаралды 1,2 МЛН
Asyncio in Python - Full Tutorial
24:59
Tech With Tim
Рет қаралды 31 М.
Python 101: Learn the 5 Must-Know Concepts
20:00
Tech With Tim
Рет қаралды 1 МЛН
Python's 5 Worst Features
19:44
Indently
Рет қаралды 31 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 262 М.
All 39 Python Keywords Explained
34:08
Indently
Рет қаралды 42 М.
Every programming language explained in 15 minutes | Prime Reacts
43:42
Python Object Oriented Programming (OOP) - For Beginners
53:06
Tech With Tim
Рет қаралды 3,2 МЛН
Modern Python logging
21:32
mCoding
Рет қаралды 136 М.
X86 Needs To Die
1:09:15
ThePrimeTime
Рет қаралды 304 М.
10 Minutes To Escape Or This Room Explodes!
10:00
MrBeast
Рет қаралды 64 МЛН