Generators in Python || Python Tutorial || Learn Python Programming

Поделиться
HTML-код
  • Опубликовано: 28 сен 2024
  • 𝙎𝙩𝙖𝙮 𝙞𝙣 𝙩𝙝𝙚 𝙡𝙤𝙤𝙥 𝙄𝙉𝙁𝙄𝙉𝙄𝙏𝙀𝙇𝙔: snu.socratica.... Learn how to use generators in Python. We'll cover two types: Generator Functions and Generator Expressions. Generator functions use the "yield" keyword, while generator expressions look like a "tuple comprehension." Generators are a powerful and efficient tool for use when looping over large amounts of data.
    We were able to bring you this video thanks to our generous Kickstarter backers! Find their names hidden (okay, not very hidden) in the video!
    Socratica Friends, we have a quiet little email group for Python if you'd like to receive updates (can't count on YT for notifications). Sign up here: snu.socratica....
    ⧓⧓⧓⧓⧓
    Subscribe to Socratica + bell for notifications:
    bit.ly/Socratic...
    Find our programming playlists here:
    Python programming: bit.ly/PythonSo...
    SQL programming: bit.ly/SQL_Socr...
    ⧓⧓⧓⧓⧓
    We recommend:
    How to Be a Great Student
    ebook: amzn.to/2Lh3XSP
    Paperback: amzn.to/3t5jeH3
    Kindle Unlimited (read free): amzn.to/3atr8TJ
    Python Cookbook, 3rd edition
    amzn.to/3goRmbG
    The Mythical Man Month - Essays on Software Engineering & Project Management
    amzn.to/2tYdNeP
    Shop Amazon Used Textbooks - Save up to 90%
    amzn.to/2pllk4B
    ⧓⧓⧓⧓⧓
    Join this channel to get access to perks:
    / @socratica
    Support Socratica on Patreon:
    / socratica
    ⧓⧓⧓⧓⧓
    Python instructor: Ulka Simone Mohanty (@ulkam on Twitter)
    Written & Produced by Michael Harrison
    #Python #Generators #Coding

Комментарии • 183

  • @Socratica
    @Socratica  2 года назад +9

    Wear a Socratica Python shirt for good luck coding: shop.socratica.com/products/python-by-socratica

  • @ekandrot
    @ekandrot 2 года назад +20

    To speed up the prime generator, don't add 2 to cache, because all numbers tested are odd and therefore compare false. In the inner loop between line 13 and 14, break if n < p*p - this will have the biggest speedup, because it will only check up to the sqrt of n. So 3 would be added without checks, 5 through 9 will only compare against the number 3. 11 through 25 only using numbers 3 and 5. Etc. vs using all of the numbers in the cache to find each new prime.

  • @rio_agustian_
    @rio_agustian_ 2 года назад +44

    FINALLY! Another python tutorial

  • @Socratica
    @Socratica  2 года назад +22

    You can "stay in the Python loop" by signing up for our Python newsletter: snu.socratica.com/python

    • @anujkondhalkar9776
      @anujkondhalkar9776 2 года назад

      All I have to say that those python videos from your channel are best. Would you make a complete course laylist from beginner to advanced. Some time it feels like you made it because you get pleasure frome it. Thank You for your efforts.

  • @markrobinsontraining
    @markrobinsontraining 2 года назад +66

    I've learnt so much from your videos; they are as informative as they are fun. Thanks so much!

  • @murphygreen8484
    @murphygreen8484 2 года назад +68

    I look forward to contributing to the acquisition of a human

    • @Socratica
      @Socratica  2 года назад +17

      We know they're out there!! 💜🦉

  • @lxathu
    @lxathu 2 года назад +5

    Never was so much owed by so many to so few for so short but so informative videos.

  • @laurentgauthier8742
    @laurentgauthier8742 2 года назад +5

    Those python videos and their slightly different approach are always crystal clear and interesting. Thank you very much for your work!

  • @theepicguy6575
    @theepicguy6575 2 года назад +8

    that patreon addition was real smoooth!
    very infomative nonetheless. did expect yield with somewhere cause i stagger there

  • @youssefelamrani7905
    @youssefelamrani7905 2 года назад +2

    Shit since I started python i've never understood generators like this, it's amazing that we have Socratica to be honest thank you so freaking much

  • @rrahll
    @rrahll 2 года назад +5

    best artificial intelligence visualization in the world.
    Thanks for the tutorial )

  • @stuarthys9879
    @stuarthys9879 2 года назад +1

    I had never considered generating generators, but if I generate any ideas I will iterate until I return a tractable solution. Thanks for the video. I appreciate the ones that are aimed higher than beginner level!

  • @serta5727
    @serta5727 2 года назад +5

    It seems some knowledge was generated in my head :)

  • @BrianSwatton
    @BrianSwatton 8 месяцев назад

    I really enjoy the way these are presented. Clear and informative too.

  • @SanataniAryavrat
    @SanataniAryavrat 2 года назад +1

    Good to see "Ulka Mohanty", the robotic actor

    • @snoopstp4189
      @snoopstp4189 2 года назад

      willing to admit Ulka is half the reason I watch these...

  • @shudiptosekharroy651
    @shudiptosekharroy651 2 года назад +3

    Thanks!

    • @Socratica
      @Socratica  2 года назад +2

      Thank you for your support, kind Socratica Friend!! 💜🦉

  • @PunmasterSTP
    @PunmasterSTP 2 года назад

    Generators in Python
    generating interest.
    The amount of education in Socratica's videos
    Is indeed intense.
    Expense
    -s seem,
    Like what they have a lot.
    Let's help them out
    And give it a thought.
    Bot,
    Is what they're not using.
    Care,
    Is what they give.
    If they kept making videos till the end of time,
    Then knowledge would always live!

  • @IvanTheChemist
    @IvanTheChemist 2 года назад +1

    I wanted this video like a month ago! Great job and a bunch of thanks!

  • @pokerchannel6991
    @pokerchannel6991 8 дней назад

    I love the production process. I love you

  • @mihalynemes4243
    @mihalynemes4243 2 года назад +2

    A small optimization for the generation of prime numbers: instead of storing the found ones in a list, you could put them in a set.

    • @stuarthys9879
      @stuarthys9879 2 года назад

      I’m curious, why would this improve performance?

    • @mihalynemes4243
      @mihalynemes4243 2 года назад +1

      @@stuarthys9879 It is much quicker to look up a member in a set than in a list.

    • @Daniel_WR_Hart
      @Daniel_WR_Hart 2 года назад

      That's only if you're looking for the presence of one specific item. All found primes need to be checked anyways to verify the current number, so it wouldn't matter in this case.

    • @mihalynemes4243
      @mihalynemes4243 2 года назад

      @@Daniel_WR_Hart Yes, you're right!

  • @jemzhatfelid5522
    @jemzhatfelid5522 2 года назад

    I'm pretty new to python and I'm trying to learn more about the language. This video was super well done and easy to understand, and I learned exactly what I wanted to. Also that circuit board dress is so cool!

  • @thegenxgamerguy6562
    @thegenxgamerguy6562 2 года назад +4

    How to speed up:
    1. Don't put 2 into the cache, because iterating 3 by 2 never results in an even number
    2. Use the fact that all prime numbers greater than 3 are congruent to 1 or 5 mod 6 (you can massively speed up)
    3. Only iterate up to square root of (n) when checking for primeness
    This will give you a massive speedup.

    • @hackerxxspacex6935
      @hackerxxspacex6935 2 года назад

      Can you please explain point number 2 and 3.

    • @thegenxgamerguy6562
      @thegenxgamerguy6562 2 года назад +1

      @@hackerxxspacex6935
      Of course.
      Ad 2):
      All prime numbers > 3 are either 6k+1 or 6k-1 where k is a natural number.
      Examplea:
      7 = 6 * 1 + 1
      11 = 6 * 2 - 1
      It's important though that of course not all numbers of one of those forms are prime, but you can exclude a large portion of the natural numbers from the division (actually: modulo) testing. I also use this to unroll my loop when I need a quick and dirty prime number test, because I do loop = loop + 6 and then the two divisions (sieving only requires prime numbers as divisors).
      Saying they are congruent to either 1 or 5 mod 6 is the same sentence, just shorter.
      Oh, and also I do a preliminary check if n mod 6 is either 1 or 5 to weed out many n before even starting to loop. Thats helpful, too.
      Ad 3):
      If you want to test n for primeness you only need to do division testing up to the square root of n (sqrt(n)) because sqrt(n) * sqrt(n) is already n.

  • @nirajabcd
    @nirajabcd 2 года назад

    seriously these videos are on another level..

  • @Daniel_WR_Hart
    @Daniel_WR_Hart 2 года назад

    To answer the question weighing on everyone's mind, it is possible to create a generator that generates generators:
    import itertools
    def gens():
    yield itertools.count(1, 5)
    yield itertools.count(10, 3)
    yield itertools.count(20, 2)
    for gen in gens():
    for x in gen:
    print(x)
    if x > 30:
    break

  • @Jawahar-Engr.
    @Jawahar-Engr. 2 года назад

    Thank You AI Teacher... Now iam Confident enough in dealing with python generator 😃❤

  • @MaximoPower2024
    @MaximoPower2024 2 года назад +2

    Why do you call close() method instead using break in order to stop the for loop?

  • @bugsolar4610
    @bugsolar4610 2 года назад

    Love and learnt so much from your videos,
    Want videos on Multithreading, multiprocessing, Class and static methods, public private and protected methods, super keyword.

  • @abyss2200
    @abyss2200 2 года назад +1

    Got a bit late, was so tired lately
    How's Socratica💝

  • @amauta5
    @amauta5 2 года назад +1

    I always love this series!

  • @KnightAmine
    @KnightAmine Год назад

    OMG ! Thanks alot! Clearer, it could not be ! 🙏

  • @FilterYT
    @FilterYT 2 года назад

    I would like to compliment the presenter, thank you.

  • @karim-gb5nx
    @karim-gb5nx 2 года назад

    This is actually impressive

  • @daniellow426
    @daniellow426 2 года назад

    Learning a lot from you folks. Thank you.

  • @AhmadAsmndr
    @AhmadAsmndr 2 года назад

    I am very happy to see you again with another amazing video. thank you very much

  • @RichardGreco
    @RichardGreco 2 года назад

    Another great python tutorial. You should develop another way to accept financial support. I know someone is taking a big cut somewhere and I'd rather not give them anymore right now.

  • @skilz8098
    @skilz8098 2 года назад +1

    I'd like to see an Assembly Tutorial from this channel!

    • @theblindprogrammer
      @theblindprogrammer 2 года назад

      What is Assembly used for these days? I thought C replaced Assembly

    • @skilz8098
      @skilz8098 2 года назад

      @@theblindprogrammer It can be used for a lot of things, especially when you are designing your own ISA...

  • @__raghu.vir_
    @__raghu.vir_ 2 года назад

    Good job, ❤️from india

  • @piotrmazgaj
    @piotrmazgaj 2 года назад

    This is gold!

  • @gvimvim
    @gvimvim Год назад

    this footage is awesome

  • @ihateorangecat
    @ihateorangecat 2 года назад +3

    welcome back !!
    waiting for more python tutos...
    so much love from Myanmar🤍🤍🤍

    • @Socratica
      @Socratica  2 года назад

      Hello to our Socratica Friends in Myanmar!! 💜🦉

  • @hanfmampf1234
    @hanfmampf1234 2 года назад +1

    Seems like magic to me

  • @alexgora7530
    @alexgora7530 2 года назад

    LOVE YOUR WORK!!!

  • @alinaderiparizi7193
    @alinaderiparizi7193 5 месяцев назад

    another awesome!

  • @ubertcoolie8694
    @ubertcoolie8694 2 года назад

    Thanks for the video, it is great!

  • @infinityinf1
    @infinityinf1 2 года назад +1

    Yes, it is possible to generate generators that generate generators.

  • @ssh17hx0r
    @ssh17hx0r 2 года назад

    This is fantastic!

  • @TheZayzoo
    @TheZayzoo 2 года назад

    Is there a video on args and **kwargs

  • @chriss3154
    @chriss3154 Год назад

    Hmm maybe Socratica is the generator of all generators...not sure though cant fit the entire list in my memory😁

  • @nullsemicolon
    @nullsemicolon 2 года назад

    Great video!

  • @SergiiStarodubtsev
    @SergiiStarodubtsev 2 года назад

    very nice!

  • @douglassoaresmantova
    @douglassoaresmantova 2 года назад

    I love this channel

  • @samuelnnanna2539
    @samuelnnanna2539 2 года назад

    the prime_number program is not for prime numbers but odd number, there is no code here checking for prime number

  • @omarcruz6326
    @omarcruz6326 2 года назад

    Python Videos are back ! 😍

  • @yonatantre
    @yonatantre 2 года назад

    please please make a js tutorial u r the best

  • @saurabhkhandekar2786
    @saurabhkhandekar2786 2 года назад

    What is the name of background music ?

  • @sebavergarasassi6462
    @sebavergarasassi6462 2 года назад

    ¡Gracias!

    • @Socratica
      @Socratica  2 года назад

      Thank you for your kind support!! 💜🦉

  • @Sneaky-Sneaky
    @Sneaky-Sneaky 2 года назад

    I joined this channel primarily to watch your Python videos. They are relaxing and stimulating simultaneously. After 20 years as a software engineer, it is quite unexpected !
    For each video()
    Smile = Smile + 100
    Next
    Print(Smile)
    3700. #my face hurts ! Thank you! ….. my I have another please ?
    If answer = “Not now or in any other space in time”
    Then 😢😭
    Else 🖖🏼

  • @vishnuhari8713
    @vishnuhari8713 Год назад

    Thanks

    • @Socratica
      @Socratica  Год назад

      Gosh you are so kind, thank you for your well wishes and your support! Much appreciated! 💜🦉

  • @rara4
    @rara4 2 года назад

    I was there !

  • @olssonolov
    @olssonolov 2 года назад

    All prime numbers> 3 can be written as 6n +/- 1.

    • @markk4203
      @markk4203 2 года назад

      n = 4 doesn't work (25 is not prime)

    • @olssonolov
      @olssonolov 2 года назад +1

      @@markk4203 I did not say that it works for all n.

  • @pile333
    @pile333 2 года назад +1

    Socratica's favorite Python one liners?

  • @stevenwilson5556
    @stevenwilson5556 2 года назад

    Generate a generator, that generates generators… sounds like a Von Neumann probe (aka self-replicating spacecraft).

  • @michap.fertig3656
    @michap.fertig3656 2 года назад

    So what are the cons of generators?

    • @josephgaviota
      @josephgaviota 2 года назад

      Generators make DC, whereas alternators make AC; making it easier to step-up or step-down voltages.

  • @MrWeaver69
    @MrWeaver69 2 года назад

    I knew i know her...well least her voice....She is the voice of Echo in Crackdown....finally i have a face match the voice...I did not know she is an actress.

  • @gavin1327
    @gavin1327 2 года назад

    Or do I?

  • @JorgeEscobarMX
    @JorgeEscobarMX 2 года назад +1

    I haven't started this playlist. I'm kinda scared of python now.

    • @elihodges5593
      @elihodges5593 2 года назад +1

      Don't worry about it. Start from the beginning and the mist will lift. Just always make some small project that lets you use the concepts in the video practically.

    • @nonconsensualopinion
      @nonconsensualopinion 2 года назад

      Don't be. Socratica makes it simple if you start with the first video in the series. You can do it and it will only take a few hours to get through all the videos.

  • @leesweets4110
    @leesweets4110 2 года назад

    I want to write a program that will intuit all of my programming needs and write the code for me.

  • @ulvessens5902
    @ulvessens5902 2 года назад

    Man, that's a scary thumbnail!

  • @crazytimes3512
    @crazytimes3512 2 года назад

    so crates

  • @jeffschroeder4805
    @jeffschroeder4805 2 года назад

    What is going on with all the "shorts" on your channel? I keep expecting real videos with more content. I contributed so you could provide more videos but these are more like click bait, very disappointed. Yours isn't the only channel, I find them mostly a waste of time.

  • @Matthew-vw6gy
    @Matthew-vw6gy 2 года назад

    So much editing

  • @tmsedustore4028
    @tmsedustore4028 2 года назад

    are you human or Ai ? i have been wondering

  • @fuddyduddy
    @fuddyduddy 2 года назад

    900th Like!!

  • @SuperlativeCG
    @SuperlativeCG 2 года назад

    They're everywhere.

  • @andrewballr
    @andrewballr 2 года назад +34

    These videos are absolutely brilliant.I like the format, short easily digestible videos on a very specific feature of python.

  • @lxathu
    @lxathu 2 года назад +1

    Thanks!

    • @Socratica
      @Socratica  2 года назад

      Thank you for your kind support! Köszönöm!

  • @satoriblue1349
    @satoriblue1349 2 года назад +25

    I've been watching your videos for about 5 years now and I just want to let you know that I now have a great full-time job as a consultant and am invaluable to my team thanks to my ability to code, which in part is thanks to you!

    • @skwerone
      @skwerone Год назад

      I got a question. I got an unusual tech Stack and don't know what position I should be submitting to. I know how to code in python mainly scraping, organizing data, sending API requests, formatting texts. I also know SEO, copywriting, creating websites and also 3D modelisation and motion graphics. I'm good at all what I mentioned.

    • @anonfourtyfive
      @anonfourtyfive Год назад

      @@skwerone Hi,
      You're currently in the same path that I am.. Just saying.
      We are searching the same things ( Probably more people than we think are trying )
      I'm now speaking Python, and wish to find people to speak with.
      If you want, respond me back, I use selenium with tkinter GUI strap in a beautiful OOP structure,
      You'll understand.
      Kindly, Guillaume. ( William )

    • @jay_wright_thats_right
      @jay_wright_thats_right 9 месяцев назад

      @@skwerone can't anyone tell you what to do. Learn who you are and what you love to do then research multiple roles. I can cook but that doesn't mean I want to be a chef.

  • @Tuxiswatching
    @Tuxiswatching 2 года назад +7

    The prime generator will be way more efficient, if you only check until the square root of n is reached.

    • @Daniel-ng8fi
      @Daniel-ng8fi 2 года назад +2

      yeah, that would be a big speed up. Also (this wont really have any effect) you don't need 2 in the prime_cache as every number you are testing is odd

    • @kquat7899
      @kquat7899 2 года назад +1

      This was covered in an earlier video in the series.

  • @АлексейБаскинов
    @АлексейБаскинов 2 года назад +8

    A similar Haskell tutorial would be both a challenge for Socratica and a valuable source of knowledge for those who want to learn the language.

  • @danielbadra9447
    @danielbadra9447 2 года назад +4

    No programing tutorial channel has such well written and engaging videos.

  • @Ghostaladdin
    @Ghostaladdin 2 года назад +3

    Your videos really are the best - I have watched them over and over again as they are as entertaining as they are educative. Really really learned a lot. Thank you thank you for all the work you put into creating this masterpiece (officially my favorite videos on coding hands down!)
    One quick ask, if you'll indulge me - could you possibly make something on Linked Lists, Binary Trees (in that order). Seen so much content on these but I bet hearing it from you would make it that much easier to digest/understand. Looking forward to this.

  • @kirbymarchbarcena
    @kirbymarchbarcena 2 года назад +8

    ME: Another great lesson, what can you say about this?
    PYTHON: Hissssssss!

    • @skilz8098
      @skilz8098 2 года назад +1

      How did a python turn into a hydra? Generators!

  • @qizhenggu20
    @qizhenggu20 2 года назад +2

    “is_prime” in code could be replaced by a for-else statement

  • @vadymvv
    @vadymvv 2 года назад +3

    I'm not a noob in programming, but i was strugle to understand yield in functions. Thanks to you all is clear now!

    • @Socratica
      @Socratica  2 года назад +1

      This is wonderful to read, thank you for telling us! 💜🦉

    • @sadhappy8860
      @sadhappy8860 Год назад

      It's odd isn't it, with programming someone will say the right words or use the right analogy for it to make sense. That table Tennis analogy is great!

  • @vikranttyagiRN
    @vikranttyagiRN 2 года назад +2

    Always great tutorials from this channel. Really appreciated

  • @pile333
    @pile333 2 года назад +1

    Generator of a generator?
    Mmm it sounds redundant.

  • @BobP-ks1mu
    @BobP-ks1mu Год назад +1

    So happy I found your channel. Great video...I like your approach to teaching and how you break things down and provide several examples. The information provided has greatly improved my understanding!

  • @MrOvipare
    @MrOvipare 2 года назад +1

    I've known Socratica with the excellent abstract algebra videos, glad to see that the Python series is just as good!

  • @Hardzinho_Yay
    @Hardzinho_Yay Год назад

    The most important thing Ilearned in this video is how 'yield' is properly pronounced

  • @GIULI4994
    @GIULI4994 5 месяцев назад

    this is the best video I've watched about generators! such an important but somehow slippery concept to explain

  • @volbla
    @volbla 10 месяцев назад

    I recently found out about the "yield from" expression. You can use it to create generators with a recursive definition.

  •  2 года назад +1

    Awesome and helpful video! Great work 🥰

  • @jhuyt-
    @jhuyt- 2 года назад +1

    Instead of using a sentinel value in the inner for loop of the prime generator, you can use the `for ... else` construction. It's relatively unknown but it's perfect for this

  • @ehudkotegaro
    @ehudkotegaro Год назад

    maybe instead of looping over the primes in primecache you can define a variable fact=2 before the first loop, that will contain (n-1)! Than to check if n is prime we check weather (fact+1)%n==0, and to get the next factorial we need to multiply fact by n(n+1).

  • @garrettwill1220
    @garrettwill1220 Месяц назад

    My video buffered at 6:29 which was where the generator was created and run without an exit condition so I thought the buffering was a meme and part of the video. Additionally I am looking for help using the from command with generators which was not covered at all in this video.

  • @AlbertoAvilaGarcia
    @AlbertoAvilaGarcia 4 месяца назад +1

    embedded humor in these videos is proportional to the love they cook them with 🥰

  • @nano7586
    @nano7586 2 года назад

    Quite funny videos but 8 minutes for a rather easy concept is a bit too much I'd say.. we are slowly (finally) reaching an era on RUclips where people realize that viewers don't like talking and prefer when it gets to the point.

  • @ilkhomibrokhimov4729
    @ilkhomibrokhimov4729 2 года назад +1

    Thanks

    • @Socratica
      @Socratica  2 года назад

      Thank you for your kind support! We're so glad you're watching!! 💜🦉

  • @conzymaher
    @conzymaher 10 месяцев назад

    Very helpful video and the style is hilarious. love it! Subscribed

  • @raphaelprates1500
    @raphaelprates1500 Год назад