10 Python Comprehensions You SHOULD Be Using

Поділитися
Вставка
  • Опубліковано 26 січ 2025

КОМЕНТАРІ • 143

  • @TechWithTim
    @TechWithTim  10 місяців тому +6

    To learn programming and Python - check out Datacamp!
    💻 Learn Python - datacamp.pxf.io/anvmQo
    💻 Learn Programming - datacamp.pxf.io/k0D3G3

    • @DarinCox-or1iq
      @DarinCox-or1iq 10 місяців тому

      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 10 місяців тому

      could you do javascript beginner to pro challenges on code wars or anyotherway

    • @MiAmigoKier
      @MiAmigoKier 10 місяців тому

      May I ask, what is your keyboard, it sounds great btw

    • @DarinCox-or1iq
      @DarinCox-or1iq 10 місяців тому

      Ok

    • @gameslp7583
      @gameslp7583 8 місяців тому

      boy do you know str.startswith() and str.endswith ?

  • @kerrykreiter445
    @kerrykreiter445 10 місяців тому +27

    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!!

  • @Indently
    @Indently 10 місяців тому +4

    07:28 I actually never knew you could insert multiple conditions like that, pretty cool!

    • @RadChromeDude
      @RadChromeDude 8 місяців тому

      what's the difference between that and simply chaining the conditions together with the "and" operator?

  • @whiteedward1
    @whiteedward1 8 місяців тому +5

    I've barely learned anything in python and easily picked up the information. So simple, yet elegant explanations. Thank you. It has already helped me in my assignments.

  • @RadChromeDude
    @RadChromeDude 8 місяців тому +1

    Man list comprehensions are just amazing. I've just finished a level 1000 coding module in python. Basically, i ended up (ab)using list compre wherever I could. It's just that elegant!

  • @mikec64
    @mikec64 10 місяців тому +3

    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.

  • @BruceDuncan
    @BruceDuncan 9 місяців тому +12

    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 9 місяців тому +1

      nah jit bro got a whole level of python knowledge but still dont know that

    • @nirty6340
      @nirty6340 9 місяців тому

      ​​@@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

    • @thirdeye4654
      @thirdeye4654 4 місяці тому

      Writing "and" is much cleaner and more readable, I find it odd that multiple if statements are valid.

  • @swagatopablo
    @swagatopablo 9 місяців тому +10

    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 9 місяців тому +4

      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 9 місяців тому +4

      @@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.

    • @natasdabsi1138
      @natasdabsi1138 7 днів тому

      Map is slower because overhead call ​@@swagatopablo

  • @eladiomendez8226
    @eladiomendez8226 10 місяців тому +48

    Is this list comprehensive of all comprehensions ? 😅

    • @gaussdog
      @gaussdog 9 місяців тому +4

      Is your comprehension comprehensive?

    • @YarPirates-vy7iv
      @YarPirates-vy7iv 9 місяців тому +2

      As a connoisseur of dad jokes I want to thank you for this contribution. 🎉

    • @NearLWatson
      @NearLWatson 9 місяців тому +5

      Comprehensive list of comprehensions to help comprehend a list of comprehensions within which the list comprehension is included.

    • @NelsonMandela-od6ut
      @NelsonMandela-od6ut 5 місяців тому

      ​@@NearLWatson Comprende?

  • @lucasseagull8282
    @lucasseagull8282 10 місяців тому +5

    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!

  • @BrianStDenis-pj1tq
    @BrianStDenis-pj1tq 10 місяців тому +5

    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 10 місяців тому

      I've always wondered about speed comparison but I have no idea how to set that one up

    • @BrianStDenis-pj1tq
      @BrianStDenis-pj1tq 10 місяців тому +1

      @@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 10 місяців тому

      @@BrianStDenis-pj1tq that's the first time I've heard of time.perfcounter()
      Ty

    • @BrianStDenis-pj1tq
      @BrianStDenis-pj1tq 10 місяців тому +2

      @@GigasAhriman BTW, I left out a character, its time.perf_counter()

    • @mikec64
      @mikec64 10 місяців тому +2

      @@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.

  • @DrDeuteron
    @DrDeuteron 10 місяців тому +6

    Nested list comp:
    >>>flattened = list(chain(*matrix))
    chain is from itertools.

    • @jamesarthurkimbell
      @jamesarthurkimbell 10 місяців тому +1

      They also have a chain_from_iterable for this case... but I agree, I'd rather just type the star

  • @BiologyIsHot
    @BiologyIsHot 9 місяців тому +24

    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]

    • @kissuko931
      @kissuko931 7 місяців тому +1

      better variable names improve comprehension

  • @andresbonelli
    @andresbonelli 10 місяців тому +7

    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...

  • @Soyosan22
    @Soyosan22 10 місяців тому +2

    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. :)

  • @igokrek1234
    @igokrek1234 6 місяців тому

    Thank you Tim. I would recommend to add a profiler to show the time execution advantage (if any) for comprehensions. That wold be nice for each example.

  • @mikespon
    @mikespon 8 місяців тому

    I love your teaching style. Very easy to follow. Thank you for all your hard work.

  • @AirLight1646
    @AirLight1646 9 місяців тому +2

    What a comprehensive guide.

  • @ricdelmar4961
    @ricdelmar4961 10 місяців тому +1

    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.

  • @zhanwenchen9238
    @zhanwenchen9238 6 місяців тому

    Your video helped me comprehend this concept. Thank you!

  • @kevinh5212
    @kevinh5212 25 днів тому

    Another outstanding tutorial!

  • @kapibara2440
    @kapibara2440 9 місяців тому +1

    Great content, like always from you. Thanks Tim! Greetings from Poland 😊

  • @TBernard-g6q
    @TBernard-g6q 3 місяці тому

    Awesome tutorial and excellently explained.

  • @VamsiPosimsetti
    @VamsiPosimsetti 9 місяців тому

    Man... I love how clean this looks

  • @dmaynor
    @dmaynor 9 місяців тому

    How does the example at &t6:30 work? you don't have to terminate login in []?

  • @OmidAtaollahi
    @OmidAtaollahi 3 місяці тому

    Great one. Tnx 🥰. If you could please compare the perfomance using timeit module, it would be perfect.

  • @mimizone
    @mimizone 8 місяців тому +1

    note that the implementation with generator that uses less memory, is slower overall

  • @stefanvanbraam4378
    @stefanvanbraam4378 9 місяців тому +1

    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

  • @Ohiostategenerationx
    @Ohiostategenerationx 10 місяців тому

    Looks good. I'm just now learning it but as far as I can tell it looks way better than the original code.

  • @temppubad-d4f
    @temppubad-d4f 8 днів тому

    great tutorial. Do we have this file on git ?

  • @andreyv116
    @andreyv116 5 місяців тому

    Multi-conditional filtering is new to me but the if-else isn't too unusual since it's just the expression-if (ternary operator) making itself known

  • @ukaszdugozima816
    @ukaszdugozima816 3 місяці тому

    Hi Tim! Great stuff!! Do you use any Python's book to create this video? If so, could you please recommend us ?

  • @tincustefanlucian7495
    @tincustefanlucian7495 9 місяців тому

    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}

  • @lesheq85
    @lesheq85 9 місяців тому

    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

  • @largewallofbeans9812
    @largewallofbeans9812 9 місяців тому

    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.

  • @nascentnaga
    @nascentnaga 10 місяців тому +1

    I did not know sum() would store the internal value. That is very interesting.

    • @mahmoudhasan6954
      @mahmoudhasan6954 10 місяців тому +1

      You can apply sum(),max(),min(), len() and other functions as well

  • @DrDeuteron
    @DrDeuteron 10 місяців тому

    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.

  • @jamesarthurkimbell
    @jamesarthurkimbell 10 місяців тому

    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.

  • @samoodie
    @samoodie 10 місяців тому +1

    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 10 місяців тому

      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".

  • @Chill018
    @Chill018 8 місяців тому

    i'm wondering is there a way to use dict comperhensions but not using a list of tuples?

  • @esrx7a
    @esrx7a 10 місяців тому +1

    Comprendre! Thanks Tim.

  • @adiaphoros6842
    @adiaphoros6842 9 місяців тому

    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]

  • @lpalanisamy
    @lpalanisamy 6 місяців тому

    In "Comprehension with Multiple Conditions", if len(string) >=2 is not needed. The following will do
    valid_strings = [option for option in options if option[0]=='a' and option[-1]=='y' ]

  • @giovannisins
    @giovannisins 10 місяців тому

    Shouldn't at 5:59 the first condition be greater than or equals to 2 like you show after?

    • @HarnessedGnat
      @HarnessedGnat 9 місяців тому +2

      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 9 місяців тому +2

      You are right, thank you

  • @sdmagic
    @sdmagic 10 місяців тому

    Very well done. Thanks!

  • @i5presnt562
    @i5presnt562 9 місяців тому

    I needed this kind of videos thx so much

  • @jackiesofir4660
    @jackiesofir4660 10 місяців тому

    This is the only way we populated list where I work.
    Literly appending is I'll advised

  • @KeithKazamaFlick
    @KeithKazamaFlick 10 місяців тому +1

    my guy tim. cheers buddy

  • @svdden_strike
    @svdden_strike 10 місяців тому

    Can you teach us how to create a CMS for a website

  • @asdfmoviesssssssssss
    @asdfmoviesssssssssss 7 місяців тому

    hey! curous about the last example where you do: sum(x**2 for x in range(10000000)) instead of sum([x**2 for x in range(10000000)]). I just tested it out, but I see that using the list comprehension is a bit faster to execute. Why is it that the execution time is slower for a more efficient approach using the generator?

    • @ClipCastHubie
      @ClipCastHubie 2 місяці тому

      The difference is about memory

  • @AlexTrusk91
    @AlexTrusk91 10 місяців тому +1

    Thanks, pretty edutaining stuff

  • @adrianbratt9927
    @adrianbratt9927 14 днів тому

    nice. thanks.

  • @krzysiekkrzysiek9059
    @krzysiekkrzysiek9059 9 місяців тому

    And these are the best kind of tips 👌

  • @PowerGumby
    @PowerGumby 3 місяці тому

    can you make an efficient fibonacci program in a list (IDK HOW)

  • @shawn445
    @shawn445 10 місяців тому

    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

  • @Kknewkles
    @Kknewkles 8 місяців тому

    Is there anything else among features of Python that is on the level of usefulness of comprehensions? I've been programming in Python for over 5 years now, and that's the only half-advanced feature of it that I'm using.
    Oh, also tiny lambdas and context managers.

  • @chinzorigyou
    @chinzorigyou 10 місяців тому +1

    Thanks

  • @RAGUNATHG-m4k
    @RAGUNATHG-m4k 10 місяців тому

    tq bro.. I have learned lot. 🥺🥺

  • @erikjohnson9112
    @erikjohnson9112 9 місяців тому

    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 9 місяців тому

      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))

  • @shapunna6151
    @shapunna6151 9 місяців тому

    Thanks a lot ❤

  • @uuuppz
    @uuuppz 7 місяців тому

    valid_strings = [option for option in options if option[0]!='a' and option[-1]!='y' ]

  • @sherwinjacob880
    @sherwinjacob880 7 місяців тому

    Brilliant!!!!!

  • @yasufadhili
    @yasufadhili 10 місяців тому +1

    Thanks alot again

  • @andiglazkov4915
    @andiglazkov4915 10 місяців тому

    Thanks 😊

  • @elatedbento
    @elatedbento 9 місяців тому

    Comprehension with multiple conditions

    • @TragicGFuel
      @TragicGFuel 9 місяців тому

      Yeah personally, these comprehensions would confuse the hell out of someone who's unfamiliar and probably would have understood the more verbose syntax easier.

  • @gogasaldadze1639
    @gogasaldadze1639 9 місяців тому

    i would prefer to use this type lis=[i for i in a if i[0]=='a' and i[-1]=='y']

  • @justliberty4072
    @justliberty4072 9 місяців тому

    I'm surprised that Tim didn't mention the time-performance benefits of using comprehensions.

  • @Da_phuc
    @Da_phuc 10 місяців тому

    Ah yeah!! Good stuff aahhhhhhhhh!! More baby boi !!!

  • @garrettsmith315
    @garrettsmith315 10 місяців тому

    A little heavy on the reverb, could use a tiny bit of bass boost to the voice as well.

    • @TechWithTim
      @TechWithTim  10 місяців тому

      Agree unfortunately my recording setup isn’t the best right now as I’m moving around

    • @garrettsmith315
      @garrettsmith315 10 місяців тому

      @@TechWithTim Great content thought...waiting for some Golang.....

  • @godwinv4838
    @godwinv4838 10 місяців тому

    thank you

  • @mikeeotool2677
    @mikeeotool2677 10 місяців тому

    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 10 місяців тому

      Check from your side, it might be you made the typo.

  • @kazmi401
    @kazmi401 10 місяців тому

    Keyboard name please.

  • @DrDeuteron
    @DrDeuteron 10 місяців тому

    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.

  • @ShadowViewsOnly
    @ShadowViewsOnly 4 місяці тому

    I might be crazy, but these comprehensions only make it harder to read code... IMO the oldschool multiline for loop is much more readable... xD

    • @tamalchakraborty5346
      @tamalchakraborty5346 4 місяці тому

      Thank god I am not the only one. Comprehensions are faster and low on memory. However, the readability is way less.

  • @ImmacHn
    @ImmacHn 9 місяців тому

    So basically, sintactic sugar for reduce/map , got it.

  • @alainleufroy
    @alainleufroy 7 місяців тому

    😊
    [
    x
    for x in [[1,2],[3],[4,5]] if len(x) >1
    for y in x if y % 2 == 0
    ]

  • @johnsensebe3153
    @johnsensebe3153 8 місяців тому +1

    Instead of [x for x in range(10)], one can simply use list(range(10)).

  • @CynicAtLarge
    @CynicAtLarge 10 місяців тому +2

    3D example would be more clear if you used different range values for each dimension.

    • @TechWithTim
      @TechWithTim  10 місяців тому +1

      Good point that was not the best example

  • @wandksitesupport2777
    @wandksitesupport2777 9 місяців тому

    i like to watch your video especially in coursecareer im trying to get a job with software engeneer

  • @timothytjerije7262
    @timothytjerije7262 10 місяців тому +2

    Good day Tim. Your text is not visible, please find a way. Your lessons are good though...

    • @TechWithTim
      @TechWithTim  10 місяців тому +1

      Hmmm turn up your resolution

    • @jeromemoutou9744
      @jeromemoutou9744 9 місяців тому

      ​@@TechWithTim the red text is quite hard to see, especially when highlighted.

    • @BoredBoy888
      @BoredBoy888 9 місяців тому

      Text is perfectly fine, just find a way to read it 😉

    • @HarnessedGnat
      @HarnessedGnat 9 місяців тому

      All text colors look fine on this tablet. Adjust monitor, or try a different one.

  • @lamborghinicentenario2497
    @lamborghinicentenario2497 10 місяців тому

    Didn't even know this wizardry existed

  • @AnatoliyRU
    @AnatoliyRU 9 місяців тому +2

    for first `values = list(range(10))` is better

  • @mbnyc5401
    @mbnyc5401 8 місяців тому

    c# does it so much getter

  • @shahibm-v6n
    @shahibm-v6n 5 місяців тому

    nice

  • @newh1ve39
    @newh1ve39 10 місяців тому

    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 9 місяців тому

      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.

    • @LiamInviteMelonTeee
      @LiamInviteMelonTeee 9 місяців тому

      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)

  • @Heavy_Lvy
    @Heavy_Lvy 7 місяців тому

    values = list(range(10))👀👀👀👀👀👀

  • @CryptoBuilders
    @CryptoBuilders 10 місяців тому

    is this pythonic?

  • @thedebatemechannel4746
    @thedebatemechannel4746 Місяць тому

    Keep in mind if Elon Musk were to do this that means that the Young Turks channel wouldn't have to worry about views. Now obviously the staff would be at risk because if they're not making enough money to pay their staff then they'd have to do layoffs but how does that affect the founders? You pay off the two people at the top and then nobody else matters.
    Over time they maybe build a new audience and if they're doing enough damage Elon Musk can get other billionaires to chip in and feed them more money and build up this Trojan horse. A conservative controlled progressive channel. I don't think a lot of people realize how dangerous the moment we are in right now. The right wing is only a very few moves away from a massive checkmate and if they make these moves it's going to be lights out for the left even more than it already is. Their voices will be reduced to less than a whisper. Corporate media will be fully taken over, independent media will be taken over in a major way. So the bubble that the right wing are in will extend all the way to the left to some degree.

  • @eeknud
    @eeknud 6 місяців тому

    Ummmm, use LISP…

  • @Sanjay-tiwary
    @Sanjay-tiwary 10 місяців тому

    Hi

  • @HarnessedGnat
    @HarnessedGnat 9 місяців тому +1

    Hi Tim,
    I would enjoy watching just as much without the orange jiggy transitions… not needed IMO. (Overstimulated) Tx!

    • @HarnessedGnat
      @HarnessedGnat 9 місяців тому

      After posting that I also noticed that because we are learning to read code (as well) we’re watching REALLY closely…

  • @MW-cs8zd
    @MW-cs8zd 10 місяців тому

    Turn that frown upside down

  • @rudiklein
    @rudiklein 9 місяців тому

    I preferred the more verbose code until I saw this video.

  • @FentForEnt
    @FentForEnt 7 місяців тому +1

    4:09 that isnt easier, nothing is clear

  • @chrisw1462
    @chrisw1462 10 місяців тому +6

    You're doing something as complicated as Comprehensions, but you use multiple If's instead of Boolean operators??? ROFL

  • @eeknud
    @eeknud 6 місяців тому

    Still waiting for a reason to need, never mind use python.

  • @RebelinhoKZ
    @RebelinhoKZ 10 місяців тому +1

    chatGPT just killed all these tutorial videos....