No video

Python Yield Keyword??

  Рет қаралды 128,803

b001

b001

Күн бұрын

⭐ Join my Patreon: / b001io
💬 Discord: / discord
🐦 Follow me on Twitter: / b001io
🔗 More links: linktr.ee/b001io
Background Music:
Gentle Lo-Fi Vlog Background Music | Cookies by Alex-Productions | onsound.eu/
Music promoted by www.free-stock...
Creative Commons / Attribution 3.0 Unported License (CC BY 3.0)
creativecommon...

Пікірлер: 112
@cn-ml
@cn-ml Жыл бұрын
I think you missed a couple of essential properties of the yield statement and generator functions: 1. You can use a generator (yield keyword) to easily create custom iterables to use in for loops 2. You can also "yield from" other iterables, so you can omit the "for line in lines: yield line" in favor of "yield from lines" 3. You can send data from the caller to the yield statement using the generator send function (not important for beginner tutorial)
@Enter54623
@Enter54623 Жыл бұрын
AHDHFJAICJHRBE GOOD GOD FUCK IVE BEEN LOOKING FOR A BASE PYTHON, NON-ARRAY WAY TO MAKE CUSTOM EVER CHANGING VARIABLE NAMES GOOD GOD THANK YOU FOR CALLING ATTENTION TO THIS
@erikkonstas
@erikkonstas Жыл бұрын
Iterators are also used in built-in functions such as map, any and all: def infinite_gen(): for i in range(19): yield True yield False while True: yield True g = infinite_gen() all(g) # all(g) The above is not an infinite loop! However, if you uncomment the last line, it will become one, since the False will have passed.
@d.raghul1700
@d.raghul1700 Жыл бұрын
site rip off😂
@user-yc9rp8mv5b
@user-yc9rp8mv5b 7 ай бұрын
V_I_S_I_T #######solvemyprogrammingtask #########################################V_I_S_I_T #######solvemyprogrammingtask #########################################V_I_S_I_T #######solvemyprogrammingtask #########################################V_I_S_I_T #######solvemyprogrammingtask #########################################
@michealkinney6205
@michealkinney6205 6 ай бұрын
@@Enter54623 Dude, I never knew you could use "yield from" instead of an explicit for loop. Amazing! Thank you!
@matthewosborn3093
@matthewosborn3093 Жыл бұрын
It would be really great if you could do short videos around Pandas. I love that your videos are short and to the point.
@erikkonstas
@erikkonstas Жыл бұрын
Pandas is not part of Python, though.
@mrdcool
@mrdcool Жыл бұрын
Idk about pandas but i wana see some educational shorts,not those fking double it and give to kinda things
@erikkonstas
@erikkonstas Жыл бұрын
@@mrdcool Um what does a random trend have to do with b001's content...?
@mrdcool
@mrdcool Жыл бұрын
@@erikkonstas i want to see his content more in general
@user-qp7of2kf9y
@user-qp7of2kf9y Жыл бұрын
@@mrdcool just look for other channels and subscribe if they have shorts. algorithm will do its job eventually
@jean-claudefrancoisbaroudd730
@jean-claudefrancoisbaroudd730 Жыл бұрын
Just found your channel, I dabble in datascience in python, wrote some big projects in R and MatLab but not really anymore, this is AMAZING content ! Thank You !
@ZeeKay80
@ZeeKay80 Жыл бұрын
Just discovered your channel from TikTok and came here. You have no idea how useful this commentary based examples are. Great Job!
@kvelez
@kvelez 9 ай бұрын
1:29 def fetch_lines(filename): with open(filename, "r") as file: for line in file: yield line for line in fetch_lines("./zen.txt"): print(line, end="")
@gbk_youtube5448
@gbk_youtube5448 9 ай бұрын
def fetch_lines(filename): with open(filename, 'r') as file: return file.readlines() print(*fetch_lines("filename"), end='')
@C22_
@C22_ Жыл бұрын
Kind of reminds me of text in Pokémon when talking to NPCs. Great tutorial!
@SimpleExcelVBA
@SimpleExcelVBA Жыл бұрын
Finally! And it took only 3 minutes to get the idea, thanks! Awesome work!
@gabrielreyes8324
@gabrielreyes8324 11 ай бұрын
Omg in just 3 minutes you helped me out, new sub here
@FabianBarajas
@FabianBarajas Жыл бұрын
This is shaping up to be a good channel subscription. Thanks for the post
@TheGoldenPro
@TheGoldenPro Жыл бұрын
If you want to get all the lines you can actually iterate through the generator by using a for loop like so: for line in zen: print(line)
@erikkonstas
@erikkonstas Жыл бұрын
Yes, but here we want to demonstrate generators.
@sammy709
@sammy709 Жыл бұрын
@@erikkonstas That is a very important feature of generators though, the fact you can iterate through like that. Calling next() for an arbitrary amount of times isnt very useful
@LethalLuggage
@LethalLuggage 8 ай бұрын
@@erikkonstasI think you missed the fact that "zen" here is a generator.
@erikkonstas
@erikkonstas 8 ай бұрын
@@LethalLuggage I think what I wanted to say was that that fact was obscured by the loop.
@LethalLuggage
@LethalLuggage 8 ай бұрын
@@erikkonstas fair. I definitely felt it was missing from the video though. Like the person above me said there's very rarely a "call the next thing several times" (unless you're doing number generation) but more commonly a need to iterate over the entire item ala for loop
@keifer7813
@keifer7813 Жыл бұрын
This was better than most videos ive seen explaining this, and in a fraction of the time too
@turtlethom9127
@turtlethom9127 Жыл бұрын
Love your channel! Been binging all your vids on Python!
@bladman9700
@bladman9700 Жыл бұрын
doesnt readlines() does the same thing? 0:50
@b001
@b001 Жыл бұрын
Yes it does. I wanted to have the for-loop in both the regular function and the generator function so it's easier to see what changes between them.
@bladman9700
@bladman9700 Жыл бұрын
@@b001 oh..
@SuadoCowboy
@SuadoCowboy Жыл бұрын
Great tutorial although it would be even more helpful if you could include a for loop at the end to enhance the understanding.
@Aborrajardo
@Aborrajardo Жыл бұрын
Hey, awesome explanation and I loved the example! TY man 👍🏻
@Lector_1979
@Lector_1979 10 ай бұрын
Thanks. Excellent video.
@dariofairhall2695
@dariofairhall2695 Жыл бұрын
Finally understood yield, thanks b001
@garciajero
@garciajero Жыл бұрын
Really good explanation , i've been meaning to understand yield for a long time.
@MechMK1
@MechMK1 Жыл бұрын
A much better example is a function tjat calculates the fibonacci sequence, as it is impossible to calculate everything at once. Generators really shine in situations where returning an entire set is infeasible or even impossible
@erikkonstas
@erikkonstas Жыл бұрын
If you really need to deal with so-called "infinite lists", you're better off with a language with lazy evaluation like Haskell.
@chaddrobertson5805
@chaddrobertson5805 Жыл бұрын
Short and sweet. You make fantastic videos.
@robsc7493
@robsc7493 Жыл бұрын
def getlines(file): with open(file, ‘r’) as rfile: for line in rfile: yield line Text = getlines(“myfile.txt”) While True: Line = (next(Text)) If Line == “what I’m looking for”: Print(“found”, Line) break
@digvijaymahamuni7722
@digvijaymahamuni7722 7 ай бұрын
Just the content I needed
@rahlok8271
@rahlok8271 7 ай бұрын
Fabulous video, thank you!
@detached9
@detached9 Жыл бұрын
great way of explaining it! thanks!
@StupidChess0
@StupidChess0 Жыл бұрын
Noice video taught me a new concept. Thanks
@KonradGolinski
@KonradGolinski Жыл бұрын
Hi! What font & VSCode theme do you use?
@jamesogletree5257
@jamesogletree5257 10 ай бұрын
I found you description of Python scopes very helpful, thanks. I also like the theme color you use. What the name of your theme color?
@b001
@b001 10 ай бұрын
SynthWave’84
@bapinchakraborty5329
@bapinchakraborty5329 6 ай бұрын
Excellent video. It was really helpful. BTW could you please tell me what's that vs code theme you're using?
@b001
@b001 6 ай бұрын
SynthWave’84
@bapinchakraborty5329
@bapinchakraborty5329 6 ай бұрын
@@b001 Thanks a lot. Love your videos 👍👍
@williamsquires3070
@williamsquires3070 Жыл бұрын
Okay, but won’t this hold the file open until all the lines have been read anyway? And what if the client code using the fetch_lines() function quits (or hangs) before reading all the lines?
@appelnonsurtaxe
@appelnonsurtaxe Жыл бұрын
> won’t this hold the file open until all the lines have been read anyway Yes, the file will be open, but having an open file don't cost a lot of memory. An open file, from your OS's perspective, is just a path associated with the position of a kind of cursor that tells where you are. The OS doesn't eagerly load the entire file at once in memory, it's your job to ask it to read data. > what if the client code using the fetch_lines() function quits The next function raises a "StopIteration" exception when called on a generator that is depleted (you can also give it a second argument, in which case it will be returned instead). If the generator raises an exception on its own, calling "next" will raise it too > or hangs The "next" function will simply block until the generator unblocks itself.
@terciary
@terciary Жыл бұрын
Hmm. So, file by default iterates by lines, not by characters?
@tejken
@tejken Жыл бұрын
You are correct. Also, he could just call file.readlines() to obtain list of lines right away but for educational purposes it's better to iterate line by line.
@sudharshanvijay2337
@sudharshanvijay2337 Жыл бұрын
Instead of yield keyword, you can use the in built readline() method in python for text files.
@erikkonstas
@erikkonstas Жыл бұрын
The point is to demonstrate generators.
@rami5801
@rami5801 8 ай бұрын
Weird question, why aren't you typing but it seems like you're copy-pasing the word by word or something?
@bavaagustin
@bavaagustin 6 ай бұрын
Solid.
@AskLucy_
@AskLucy_ 7 ай бұрын
could you please zoom in. I can't see it clearly
@sayyampervaiz2646
@sayyampervaiz2646 9 ай бұрын
amazingly explained
@Geryf
@Geryf 11 ай бұрын
I failed a capital one interview today for not knowing this yield keyword.
@adrianl7318
@adrianl7318 Жыл бұрын
Great video!
@The_Gurugram_Voyager
@The_Gurugram_Voyager 8 ай бұрын
But how to get to the millionth of the lines by using yield?? Need to call the function for a million time??
@biggestbarbiefan
@biggestbarbiefan Жыл бұрын
Hi, what's your theme?
@vanshavbhalla6210
@vanshavbhalla6210 Жыл бұрын
his theme is SynthWave '84
@nojukuramu
@nojukuramu 8 ай бұрын
I think i have found the best way to iterate a list using a function call without making complex counters outside the function hmmm
@MsPocketMonsters
@MsPocketMonsters Жыл бұрын
What happens with file as you yield? Is it opened each time? Is the file read each until the last point each time? Or if it keeps open, when does it close? How can you reset the generator?
@chaddrobertson5805
@chaddrobertson5805 Жыл бұрын
To answer your first question: The file is only opened once before the loop is started. The `open` function returns a `File` instance that only needs to be initialised once before you begin iterating. As for your second question: You don't have to close the file again provided you've used the `with` statement, as this does all the cleanup for you. If you simply used `open(filename)` without the `with` statement, you would need to explicitly close the file again, yes.
@healthsolution1710
@healthsolution1710 Жыл бұрын
Nice job
@kassu3603
@kassu3603 9 ай бұрын
What's the font he uses?
@immortalsun
@immortalsun Жыл бұрын
How do you type code without typing it? Magic?
@jokerproductions3050
@jokerproductions3050 5 күн бұрын
Bless u
@nitkarshchourasia2406
@nitkarshchourasia2406 7 ай бұрын
🎯 Key Takeaways for quick navigation: 00:54 📚 *Traditional list approach: Reading all lines into a list can lead to memory issues with massive files, causing potential memory errors.* 01:38 🔄 *Introducing the `yield` keyword: Using `yield` in a function transforms it into a generator, allowing one line at a time to be processed, efficiently managing memory.* 02:50 🧠 *Generator memory efficiency: Generators discard processed lines, minimizing memory usage, and the `next` function retrieves successive lines, offering a practical solution for large datasets.*
@abcdef-fo1tf
@abcdef-fo1tf Жыл бұрын
I don't get how this stops our program from saving the whole file. Since the generator needs to be able to output the whole file of text it's still storing it right?
@idanyel1587
@idanyel1587 Жыл бұрын
It doesn't anyway. The operating system is smart enough not to load everything from the beginning. Imagine having four large files of 1GB each, that would have meant you would lose 4GB of RAM on nothing. In fact, files are nothing but a disk entry. When you are calling open (see the open syscall from C), you are getting a pointer to a file structure which also contains a cursor (the current position in in a file). Files are also mapped in memory using the mmap system call, which reserve memory, but don't allocate it initially. You could take a look at demand paging for instance to see the connection with your curiosity. So, as a conclusion, the video is a little misleading, because the operating system deals with optimizing your memory access anyway. The real deal with this generators is when you really don't want to store more than a string with one line at a time. Then would be a problem, because you would have an array of lines, which is terrible if you don't use most of them.
@abcdef-fo1tf
@abcdef-fo1tf Жыл бұрын
@@idanyel1587 so if I have a function that had a loop where each loop yields something, would the generator store the full result or calculate on demand as next is called?
@erikkonstas
@erikkonstas Жыл бұрын
@@abcdef-fo1tf Generators don't do things while they're suspended; they only resume when you call next or send with them.
@idanyel1587
@idanyel1587 Жыл бұрын
​@@abcdef-fo1tf, on demand as I said. When yield is used, that portion of the code is suspended and when you want to use it again the old state is restored and it will continue from there.
@uiqman
@uiqman Жыл бұрын
Remember to explicitly close the file after done reading it ))!
@erikkonstas
@erikkonstas Жыл бұрын
Nope; that's the whole reason of using the context manager there, it closes it automatically.
@leventcelik6597
@leventcelik6597 Жыл бұрын
Can this be stateful somehow? Say that my application can save and load. Upon loading, can I keep the last yield?
@epsi
@epsi Жыл бұрын
Not sure what you'd have in mind here, but you'd need to manually retain the last result from your generator, which can be done using for-else: last = -1 for n in range(10): pass else: last = n print(last) # 9 If you're wondering where the yield keyword is, the built-in range class offers generator behavior that is pretty much powered by a loop like this: while start < stop: yield start start += step
@roxasxiiidravenman8312
@roxasxiiidravenman8312 Жыл бұрын
so its kinda like a linked list that is lazy loaded
@arhamsayyed9518
@arhamsayyed9518 Жыл бұрын
🙌🙌
@shaqtaku
@shaqtaku Жыл бұрын
what theme do you have for vscode?
@user-dr9xv3pv3f
@user-dr9xv3pv3f Жыл бұрын
Synthwave84
@user-kw3kc5hk8l
@user-kw3kc5hk8l Жыл бұрын
Isn't yield deprecated?
@iaminfinityiq7182
@iaminfinityiq7182 Жыл бұрын
What does open() do?
@russianyoutube
@russianyoutube 8 ай бұрын
Opens a stream to the specified file, depending on the second argument it's either an input or an output stream
@aramayiskhachatryan6528
@aramayiskhachatryan6528 Жыл бұрын
What vscode theme is this?
@GeraldIrsiegler
@GeraldIrsiegler Жыл бұрын
SynthWave '84
@samueljehanno
@samueljehanno Жыл бұрын
Interesting
@minsuksung
@minsuksung Жыл бұрын
Thanks
@FreihEitner
@FreihEitner Жыл бұрын
That looks great except it appears you must know how many lines are in the original file in order to call 'next' on each one. I'm sure there is a way (I'll keep looking) to call 'next' exactly the number of times as the number of lines.
@sollertia_
@sollertia_ Жыл бұрын
You can just keep going next until you reach the end of file which raises StopIteration
@FreihEitner
@FreihEitner Жыл бұрын
@@sollertia_ OK, so include a 'try' with an exception check to determine the end of the file? Or a 'while false' loop with the exception check?
@sollertia_
@sollertia_ Жыл бұрын
@@FreihEitner u can iterate over a generator with a for loop (for line in fetch_lines) and let python do the rest. My point is that you don't really need to know how many values a generator can generate since it will raise StopIteration to notify your try catch or for loop to stop iterating
@YuraSuper2048
@YuraSuper2048 8 ай бұрын
python yield keyword? question mark?
@softcoda
@softcoda Жыл бұрын
How do u iterate over a yield function
@yang2176
@yang2176 Жыл бұрын
I wonder if this will work : temp = next(zen) while temp : print(temp) temp = next(zen)
@mismis3153
@mismis3153 Жыл бұрын
for x in stuff: print(x) I believe that's how yield is supposed to be used
@gabi_kun3455
@gabi_kun3455 Жыл бұрын
In few words the work of "yield" is to create a function that return a iterator, a iterator is that you can use with either next() and a for-loop, that iterator synchronizes with the next() or with the for-loop, in other words, each time that the function reach "yield", it send the value that you put and then stop temporaly the function in that point, that value you'll receive in either next() or the for-loop, when the for-loop reiterate, or when the next() is called again, the function execution is restored, and then the process is repeated until the function finish, this is the real usage of "yield", a function that has "yield" inside is named "generator function", the iterator is "generator", this is a powerful feature of python since you can make a function to produce only the necessary things and then stop the execution by not iterating again, for for-loops we can use "break", and for next() we simply don't call again, there also exists "yield from" that for example is: def generator(): yield from iterable that is equivalent to: def generator(): for value in iterable: yield value putting "yield" alone is the same as "yield None" that is all you need to know about "yield"
@hjtomi_
@hjtomi_ Жыл бұрын
@@gabi_kun3455 Super useful! Thank you
@V0W4N
@V0W4N Жыл бұрын
thats why python >>>> anything else for scripting and data structures
@K9Megahertz
@K9Megahertz Жыл бұрын
Personally, I wouldn't want to read millions of lines of text with python.
@erikkonstas
@erikkonstas Жыл бұрын
Please do not propagate this mindset; every language has its benefits and drawbacks, and hence its purposes. Saying one is superior to another as an absolute is very disliked upon among software devs, since it indicates a diehard mentality.
5 Good Python Habits
17:35
Indently
Рет қаралды 508 М.
Python Generators
15:32
mCoding
Рет қаралды 135 М.
🩷🩵VS👿
00:38
ISSEI / いっせい
Рет қаралды 28 МЛН
Happy birthday to you by Tsuriki Show
00:12
Tsuriki Show
Рет қаралды 12 МЛН
Can This Bubble Save My Life? 😱
00:55
Topper Guild
Рет қаралды 87 МЛН
This Dumbbell Is Impossible To Lift!
01:00
Stokes Twins
Рет қаралды 37 МЛН
AsyncIO, await, and async - Concurrency in Python
9:12
Socratica
Рет қаралды 92 М.
Python Generators Explained
28:37
Tech With Tim
Рет қаралды 152 М.
The Fastest Prime Number Algorithm
5:23
MarshySyntax
Рет қаралды 2,7 М.
10 Important Python Concepts In 20 Minutes
18:49
Indently
Рет қаралды 67 М.
The Algorithm Behind Spell Checkers
13:02
b001
Рет қаралды 411 М.
All 39 Python Keywords Explained
34:08
Indently
Рет қаралды 163 М.
Please Master These 10 Python Functions…
22:17
Tech With Tim
Рет қаралды 142 М.
5 Useful Python Decorators (ft. Carberra)
14:34
Indently
Рет қаралды 98 М.
“typing” is getting deprecated in Python
7:20
Indently
Рет қаралды 40 М.
🩷🩵VS👿
00:38
ISSEI / いっせい
Рет қаралды 28 МЛН