6 Tips to write BETTER For Loops in Python

  Рет қаралды 244,880

Patrick Loeber

Patrick Loeber

Күн бұрын

6 Tips to write BETTER For Loops in Python.
Further resource:
Talk "a deeper look at iteration in Python": • Loop better - a deeper...
Get my Free NumPy Handbook:
www.python-engineer.com/numpy...
✅ Write cleaner code with Sourcery, instant refactoring suggestions in VS Code & PyCharm: sourcery.ai/?... *
⭐ Join Our Discord : / discord
📓 ML Notebooks available on Patreon:
/ patrickloeber
If you enjoyed this video, please subscribe to the channel:
▶️ : / @patloeber
~~~~~~~~~~~~~~~ CONNECT ~~~~~~~~~~~~~~~
🖥️ Website: www.python-engineer.com
🐦 Twitter - / patloeber
✉️ Newsletter - www.python-engineer.com/newsl...
📸 Instagram - / patloeber
🦾 Discord: / discord
▶️ Subscribe: / @patloeber
~~~~~~~~~~~~~~ SUPPORT ME ~~~~~~~~~~~~~~
🅿 Patreon - / patrickloeber
#Python
Timeline:
00:00 - Introduction
00:16 - Avoid loops
00:54 - enumerate
01:43 - zip
02:57 - Think Lazy
05:19 - Use itertools more - 3 cool functions
08:00 - Use NumPy
----------------------------------------------------------------------------------------------------------
* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you so much for the support! 🙏

Пікірлер: 163
@GooogleGoglee
@GooogleGoglee Жыл бұрын
On the other side, if you don't know the particular function (that you or someone else used) it will make the code less readable + and if you don't know all features of the functions you will get lost on finding a bug. Loops are not always bad if well designed inside a concept and using good commentary lines for descriptions/explanations.
@gritsteel4559
@gritsteel4559 Жыл бұрын
I agree, but thanks Patrick, very useful to know.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
The assumption is that you can read the manual to find out what things mean.
@alexmiller3260
@alexmiller3260 Жыл бұрын
Problem here is more deep, than you might think. This guy said "functions are optimized", but that's not a complete true. Functions can allocate extra stuff during calculations what makes such ones not optimized. Allocations could be avoided using just loops. Even if function is fully optimized you may have another flaw, because sometimes more than one operation is needed and then output from one function goes to input of another function, which now do extra calculations and may be not optimized. This is why you should not rely on those functions on 100% if you don't understand concepts of memory management and optimization
@GooogleGoglee
@GooogleGoglee Жыл бұрын
@@alexmiller3260 well the easy answer here is that partially D'Oliviero already answered you and I can say that seems you are referring to iterative and recursive functions. Of course if you are programming you have to know of how it works regarding memory management etc... It is a choice you will make at the moment and maybe refactor it along the way...
@simplyacatenjoyinglife3260
@simplyacatenjoyinglife3260 Жыл бұрын
For loops in Python are terribly slow, you should always avoid them.
@studyingasyouwere
@studyingasyouwere Жыл бұрын
Thank you for another awesome video Patrick! I found your channel watching the Snake game video and yesterday I just posted a video of making my own version of the game. Thank you for your tutorials and giving me inspiration. 🙂
@re.liable
@re.liable Жыл бұрын
Abt the generator tip, I'd argue it's better to put the generator comprehension inside the function that uses it. 1 reason is as you've shown, storing it in a variable gives the impression that it is reusable when in fact it may be exhausted in some other place. Another is that I think it's very readable that way, e.g. sum( event[1] for event in events ) I find that it reads really well with other functions too, namely `any` and `all`, e.g. all( event[1] > 10 for event in events )
@fengjeremy7878
@fengjeremy7878 Жыл бұрын
Very useful! I have always been writing inefficient and unreadble codes since I don't know these advanded methods.
@sanjaysaha1311
@sanjaysaha1311 Жыл бұрын
Pairwise & takewhile were new to me. Thanks!!
@Migoyan
@Migoyan Жыл бұрын
Generators are great to save RAM memory for large arrays or Sequences. Although they can be slower than looping on array due to the need of computing each next step. My go to is choose the most readable by default and optimize if you need to. As for islice, i largely prefer to use the slicing syntax in python which is simple, for exemple my_list[2:5:2] is equivalent of islice(my_list, 2, 5, 2).
@chaddaifouche536
@chaddaifouche536 Жыл бұрын
It is not equivalent, the slicing syntax copy the slice while islice() is a generator that doesn't copy the array. For memory use and sometimes execution speed, islice will be better.
@Migoyan
@Migoyan Жыл бұрын
@@chaddaifouche536 Didn't know that, thanks
@jorgseidel4893
@jorgseidel4893 Жыл бұрын
@@Migoyan Additionally, islice will also work on generators while the slicing syntax is specific to lists.
@Migoyan
@Migoyan 5 ай бұрын
@Bebtelovimab I see you don't need tips on being unfunny.
@Migoyan
@Migoyan 5 ай бұрын
@Bebtelovimab Ok bro, we understand you're a kid. Now you can resume your day.
@overwatch2944
@overwatch2944 Жыл бұрын
Useful tips, very good video! Keep 'em coming my friend!
@NateROCKS112
@NateROCKS112 Жыл бұрын
3:38 note that, in the generator expression, you can use tuple unpacking as well.
@shashankemani1609
@shashankemani1609 Жыл бұрын
These are amazing tips. Thanks so much!
@ChrisHalden007
@ChrisHalden007 Жыл бұрын
Great video. Very useful. Thanks
@GATEPREP
@GATEPREP Жыл бұрын
Cool Tips, thanks for sharing, Patrick :)
@Terrados1337
@Terrados1337 2 ай бұрын
Python never ceases to amaze me. Loops being slow being be a not so subtle hint that python and production should never ever ever mix.
@knowledgedose1956
@knowledgedose1956 Жыл бұрын
this is a top tier content as a "cheat sheet" video. Thank you so much, Danke schön
@champfisk5613
@champfisk5613 Жыл бұрын
Super cool man, I get more efficient every time you put out a video!
@vorpal22
@vorpal22 Жыл бұрын
Did not know about the strict parameter added to zip in Py3.10. Nice!
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
2:25 zip() is also useful with database queries. Say you have a list or tuple of field names: you can use ", ".join(field_names) to format the field names for inclusion in a “select” statement; then call dict(zip()) on the returned tuple and the field names, to create a mapping from field names to field values.
@glennmglazer
@glennmglazer Жыл бұрын
You might want to look at DictCursor which is part of the python database API and does this for you.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
@@glennmglazer I can’t see that in the standard library anywhere.
@baturin_m
@baturin_m Жыл бұрын
@@lawrencedoliveiro9104 he meant psycopg2 functionality. Don’t you use it to call db queries from your python code? I don’t believe you do it using standard library
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
@@baturin_m Not part of the “Python database API” that I can see. I have used APSW, pymysql and of course Oracle’s mysql.connector classes.
@baturin_m
@baturin_m Жыл бұрын
@@lawrencedoliveiro9104 got it. It’s strange that all of these connectors don’t provide this feature like psycopg2 does. It really helpes a lot in case you cannot use ORM for higher abstraction level.
@Chalisque
@Chalisque Жыл бұрын
Something I dealt with recently is where I wanted to loop through the lines of a text file, find the first occurrence of e.g. "hello", and then loop _from that point_ onwards, to find the first occurrence of "random", and, only if we find "random", go back through the lines between that containing "hello" and that containing "random". Iterators make it hard to consume, and harder still to backtrack, things that are easy with C's for(i=1;i
@pattty847
@pattty847 Жыл бұрын
You really always share very valuable information.
@allezvenga7617
@allezvenga7617 Жыл бұрын
Thanks for your sharing
@user-kq6mt8nk2p
@user-kq6mt8nk2p Жыл бұрын
Thank you Patrick.
@muharief3885
@muharief3885 Жыл бұрын
would be interesting if u include benchmark number also. Performance is also vital role when we do refactoring code, besides readability. For me performance is number one becoze python it self already readable by nature.
@pietraderdetective8953
@pietraderdetective8953 Жыл бұрын
A gem in a haystack! Too bad you didn't include the timeit% numbers between the optimized vs unoptimized methods. That would make the video perfect!
@miguelvasquez9849
@miguelvasquez9849 Жыл бұрын
very interesting the itertools packages, i didnt know about it.
@leandromaxado
@leandromaxado Жыл бұрын
Ward for the 1:45 tip to use later at a exam program later. Thanks, great video.
@kychemclass5850
@kychemclass5850 Жыл бұрын
Nice. Thank you.
@alekseydolia1894
@alekseydolia1894 Жыл бұрын
Hi! Regarding islice(), it's pretty enough, but the embedded list slicing is more faster and better, as for me: lines[:5] lines[1:5]
@kom_senapati
@kom_senapati Жыл бұрын
I was also thinking the same thing.
@aditya95sriram
@aditya95sriram Жыл бұрын
I think the main situation you would use islice is when you want to slice a generator. For a plain list, regular slicing in the index (as you've written) is easily understandable and also probably the most efficient. But generators don't support indexing and islice supports any iterable including generators. A small caveat that I discovered after checking the docs is that islice doesn't support negative indices but regular slicing does (e.g. last 3 elements lines[-3:])
@chaddaifouche536
@chaddaifouche536 Жыл бұрын
islice() creates an iterator over the initial array content while list slicing creates a copy (with Python lists, slicing on numpy arrays just creates alias, which sometimes results in strange behaviour, probably the reason why basic Python doesn't do it this way). On small slices this is not important but if you use big slices, in a nested loop, slicing may give a lot of work to your garbage collector.
@CodeWithTomi
@CodeWithTomi Жыл бұрын
love your videos man
@user-rx6xu6bs8c
@user-rx6xu6bs8c Жыл бұрын
Strange that you haven't mentioned, but when you want to use array elements as function arguments, you can simply write *array (most useful example: print(*array) will print all of array elements separated by spaces (use argument sep=' ' to write each value into new line) )
@kpbendeguz
@kpbendeguz Жыл бұрын
You can do that with dictionaries as well: **dict will place (key, value) pairs in the function call as optional arguments in a key=value form. However this video is about for loops and not about arrays or other data structures, so I guess that's why function calls not mentioned.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
0:47 Note that sum() just calls the objects’ ﹎add﹎ method, so in principle you could use it for strings, for example. But the function actually goes to some lengths to forbid its use with strings. I think because concatenating a sequence of strings in this way is O(N²).
@V0W4N
@V0W4N Жыл бұрын
python's strength is definetly not speed so i dont think it matters that much
@__christopher__
@__christopher__ 8 ай бұрын
for the iterator comprehension, you can get rod of those ugly indices with study_times = (minutes for task, minutes in events if task == "learn") You also won't make the error to use it twice if you put it directly in the sum call (makes more concise code, too): minutes_studies = sum(minutes for task, minutes in events if task == "learn")
@veelglorie
@veelglorie Жыл бұрын
I have some fun with itertools, but also I want to leave my answers. The firsts exercises of itertools section can be solved with: print(*lines[:5],sep=" ") print(*lines[1:5],sep=" ") print(*lines[1:5:2],sep=" ") The second with: [print(x,data[i+1])for i,x in enumerate(data[:-1])] And the last with: any(x
@siddhigolatkar8558
@siddhigolatkar8558 4 ай бұрын
Thank you
@re.liable
@re.liable Жыл бұрын
Pairwise would've been really useful in an AoC problem lol I really need to read up itertools and functools. There's so much obscure but handy stuff there
@X_x_kingfisher_x_X
@X_x_kingfisher_x_X Жыл бұрын
Short but so big Thanks.
@mayorc
@mayorc Жыл бұрын
Any advantage of using islice in your example over using slicing notation like lines[:5] for speed, memory consumption? Since it's an iterable I suppose it's convenient only for iteration purposes only. In pairwise case is it possible to skip used letters?
@aditya95sriram
@aditya95sriram Жыл бұрын
(also mentioned this in detail in another answer) islice supports generators and you can't do regular slicing in generators because you can't index into a generator
@agenticmark
@agenticmark 3 ай бұрын
Great videos so far! (this is my third video of yours today)
@aciddev_
@aciddev_ 13 күн бұрын
best for loop → for (int i = 0; i < 10; i++)
@Michael00000001
@Michael00000001 Жыл бұрын
Great video. Also for an old dog good as a reminder. np is a powerful tool (like pandas) but very annoying are their type differences, e.g. None, float, etc.
@ShotgunLlama
@ShotgunLlama Ай бұрын
Why use islice over indexing with a slice? Does it return a lazy generator instead of allocating a new sequence or something like that?
@worldwrestling2513
@worldwrestling2513 Жыл бұрын
Please tell me which plugin did you use in the design
@md.masumomarjashim
@md.masumomarjashim Жыл бұрын
I am falling in love with Python and coding in general. It allows us to do so much with so little effort, except writing the code in the first place, that is hectic but once the code is ready and everything works you feel like a super human.
@vorpal22
@vorpal22 Жыл бұрын
The more you do it, the more adept you will get at it, and when you write a truly elegant and performant piece of code (be it a function, a class, or whatever), it will feel like poetry. Same with elegant mathematical proofs. I love Python, but I prefer Kotlin because it has so much elegant, built in functional programming constructs, and functional programming can take your code and shrink its length dramatically. Python has some functional programming concepts built in, but they're a bit clunky. It's still a great language, though, if you're not worried about performance (and if you are, just make sure you use built-ins and numpy, since they're implemented in C so they run much faster than loops).
@md.masumomarjashim
@md.masumomarjashim Жыл бұрын
@@vorpal22 Guess I gotta learn Kotlin next. But trying to get into coding, I feel like I should at least spend some time with Python more before learning another language. Although the job market requires multiple languages for us to land a job, I just feel like becoming advanced in one language could perhaps be beneficial. Any thoughts?
@vorpal22
@vorpal22 Жыл бұрын
@@md.masumomarjashim I agree that you should focus on one language for awhile before moving to the next... if you really want to become a developer, you should have a strong working knowledge of at least one language, and then have some exposure to other languages so you cover your bases. You probably want to know some of each of the following: 1. Object-oriented programming 2. Procedural programming 3. Functional programming Python is - according to many surveys - the language that is in highest demand now (followed by Java, but it is declining), so it's a good choice. There's a book called "Fluent Python" that is the best I have ever looked at: it is a hefty one, but you don't have to read it cover-to-cover and it'll teach you a lot of Python than you probably didn't even know existed. O'Reilly just updated it for Python 3.10, so it's very up-to-date, and you can just skip around the chapters and learn what you need or what interests you. No Python developer should be without it. To learn Kotlin is a bit harder, because you do need to have some working knowledge of Java since Kotlin compiles into Java bytecode (same with Scala and Clojure, which are also both hybrid object-oriented and functional programming languages... Clojure is really messy, in my opinion, but it's interesting to dabble in because it makes you think about programming very differently). Keep in mind that if you know a couple languages, many companies aren't too concerned about what languages you know: you can learn one pretty quickly and it's a small investment on their part. The best thing to do is show that you have problem solving skills. There is a website called "daily coding problem" that is really valuable and covers lots of questions you'd encounter in an interview. You can sign up for free to get the problems delivered to your inbox daily (they are ranked by easy, medium, and hard), and if you pay a small fee, you can also get the best solutions to the problems the next day. Another thing that is becoming more and more popular in the hiring process is having a GitHub account with a bunch of repositories that you're working on: either personal projects, or contributions to open-source projects (I find that a bit more intimidating), school assignments, etc. It's like a programmer's equivalent of an artist's portfolio. If you don't know GitHub yet, you should take a few days to learn the basics. You usually don't need more than the basics, and if you do, you can google the answer, but it's what virtually everyone is using these days for source code repositories. Some people will probably disagree with me because we all have different opinions. How are you learning? By studying Python on your own? Do you have a reasonable background in math? You might not need to use, say, algebra much unless you get into image processing or manipulation or gaming, but math really teaches you fundamentals of thinking logically. Anyway, if you have any more questions, feel free to hit me up. Always happy to help. It was easy for me, because I got a Commodore 64 when I was five and I've been programming since then, so the huge mountain of things to know was never that insurmountable since I've been doing it for 40 years, but one thing I will warn you about: if you want to be a developer, it has to be your career as well as your hobby, because if you don't spend some of your free time keeping up with tech changes, you'll fall behind. It's kind of exhausting and stressful that way.
@daveg7388
@daveg7388 Жыл бұрын
@@vorpal22 Wow! You have such an elegant and meticulous way of writing!! I just have a single question. What should I do to be a full stack developer? What things should I learn?(not only languages but frameworks and stuff like that) I'm kinda new to programming. I have started with python before like 2 months and I think I know the basics. Does python really help me with being a full stack developer? Let me know your thoughts. Thanks!
@mariocatalano5874
@mariocatalano5874 Жыл бұрын
@@vorpal22 this is such a well thought and written comment. Trurly remarkable sir.
@MaxMustermann-on2gd
@MaxMustermann-on2gd Жыл бұрын
Regarding 6: What is the advantage of islice() instead of simply slicing the list using [start:end:step]? I guess the latter (and more widely used) is just syntactic sugar for islice()?
@lecdi6062
@lecdi6062 Жыл бұрын
islice, like a generator, does not store all the values in memory at once, so if your list is very large and you don't want to store a copy of some of it, then you should use islice. This can help save memory. However, islice should only be used when your list is big; otherwise it can actually be slower than normal slice notation as using islice requires calling a function, and in Python calling a function is very slow. In the example in the video, on my computer using Python 3.10.7, the code actually ran faster using normal slice notation than using islice.
@aouerfelli
@aouerfelli Жыл бұрын
It is not the same thing. *lst[start:end:step]* is another list than *lst* that can be modified later separately form *lst* . It is created when you use that syntax, and each item belonging to the slicing will be copied into it. If the slice is huge, you will be consuming much memory and using much copying operations just by doing *lst[start:end:step]* But if you use *slc=islice(lst,start,end,step)* nothing will be copied or calculated. When you iterate through *slc* , python will retrieve values from the original list *lst* using the indices of that slicing. You can try it yourself. l1=[1,2,3,4] l2=l1[:] then modify *l1* by reassigning values, appending, popping etc... then iterate trough *l2* , it will contain the original 1, 2, 3, 4 However if you do like this, lst=[1,2,3,4] s=islice(lst,4) then modify *lst* then iterate trough *s* , you will find that it yields the modified values.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 Жыл бұрын
Suppose I write a generator which never terminates. Then I can use islice to extract any initial part of the infinite sequence.
@aouerfelli
@aouerfelli Жыл бұрын
@@lawrencedoliveiro9104 That's an amazing idea.
@ZeroSleap
@ZeroSleap Жыл бұрын
In the zip example the equivalent would have been to do min(len(a),len(b).I still get that zip seems more convenient
@VaeV1ct1s
@VaeV1ct1s Жыл бұрын
What for should i use islice instead of [ : 5]?
@IndellableHatesHandles
@IndellableHatesHandles Жыл бұрын
If you had older RAM and CPU, would numpy's arange function be much slower? Or does the fact that it runs in C make it faster regardless?
@jorgseidel4893
@jorgseidel4893 Жыл бұрын
It will almost always make it faster on the expense of more memory consumption and binary dependency on the import.
@marcotroster8247
@marcotroster8247 Жыл бұрын
My personal tip for performance: Store everything as NumPy array and process it with Numba @njit optimized functions that are written as C-style for loops. And avoid allocation or at least allocate larger chunks at once. Good luck with optimizing your code and staying sane 😂
@shakils1921
@shakils1921 Жыл бұрын
Which VS code theme you are using?
@thepuffinbirdprotocol
@thepuffinbirdprotocol Жыл бұрын
In "is this a bug or a feature in python"(shorts) you missed a comma after "three". Think Python therefor sums three and four as one? or ignoring it? But I might be wrong....
@adekakz9794
@adekakz9794 Жыл бұрын
Can i use thi in for loops on Java? and, is it safety?
@vijaykumg
@vijaykumg Жыл бұрын
Unique features of your channel is Advanced Python course in your playlist. Which is not available in any channels.. My request to continue to do more on that topics
@patloeber
@patloeber Жыл бұрын
Thanks for the feedback! Yes that's on my list for 2023
@vijaykumg
@vijaykumg Жыл бұрын
@@patloeber Thank you.
@itsmaxim01
@itsmaxim01 Жыл бұрын
isn’t an out of range array index supposed to return undefined?
@saitejam3769
@saitejam3769 Жыл бұрын
Sir we want more python tips and tricks
@XCanG
@XCanG Жыл бұрын
Noting new, but for generator and pairwise I would unpack in for like: minutes_studied = (minutes for event, minutes in events if event == "learn") for pair0, pair1 in pairwise(...):
@sj_8811
@sj_8811 5 ай бұрын
Does anyone know the vscode theme he is using?
@dmitripogosian5084
@dmitripogosian5084 Жыл бұрын
It would be good to mention how much memory each method uses. I have seen some horrific python codes in memory requirements, compounded by the author having no idea why it uses as much memory as it does
@40.50
@40.50 Жыл бұрын
I also like shades of purple 💜
@code4l111
@code4l111 Жыл бұрын
Thanks for the tips, but tell us, what's your VS Code theme?
@danibarack552
@danibarack552 Жыл бұрын
Why use islice(lines, 5) instead of lines[:5] ?
@theannoyingone110
@theannoyingone110 Жыл бұрын
Syntax error on line 1 in thumbnail 🤓 Also nice vid
@ele6133
@ele6133 11 ай бұрын
Okay what is the vs code theme? Oh and good video, really helpful
@NikhilBhatt69
@NikhilBhatt69 8 ай бұрын
one dark pro i guess
@sonoftroy8572
@sonoftroy8572 Жыл бұрын
I’ll just keep it simple and use foreach(array $list as $key => &value); loop in php
@cmilkau
@cmilkau Жыл бұрын
Now sum() is better style than "for" anyway. But other than that, if these performance differences matter to you, don't use CPython. Use a python interpreter with a good JIT that can optimise away these differences rather than writing fine-tuned code for a slow interpreter.
@DK1PL
@DK1PL Жыл бұрын
What about recursion? p.s. It couldn’t be true that imperative language can't deal with loops or ? 🤔
@Uncle19
@Uncle19 Жыл бұрын
not sure if youve seen, but sum() does weird things with floats. for example my_list = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] sum(my_list) = 0.9999999 if you use numpy, np.sum(my_list) = 1 Can avoid some headaches this way especially when dealing with predictions of propensity where 0.001 can matter.
@djst3rling863
@djst3rling863 Жыл бұрын
consider using math.fsum() numpy is typically 3rd party, while math is built-in
@LeeK301
@LeeK301 Жыл бұрын
I learned a lot from this vid; learned even more from the comments 🐍 💬
@oriabnu1
@oriabnu1 Жыл бұрын
please write function code on cyber security and steganography
@__________________________6910
@__________________________6910 Жыл бұрын
vs code theme name ?
@vineethgk
@vineethgk Жыл бұрын
Which ide ia this? Vscode?
@djst3rling863
@djst3rling863 Жыл бұрын
Yes, VS Code w/ the "shades of purple" theme
@bokyunggg
@bokyunggg Жыл бұрын
Cool😊
@RozeFound
@RozeFound Жыл бұрын
You forgot range closing ')' in code in the thumbnail.
@notMails
@notMails Жыл бұрын
I'm thinking lazy, and didn't get a point of using "islice" instead of standart "print(line) for line in lines[1:5:2]" slicing.
@mairacristian54
@mairacristian54 Жыл бұрын
the thumbnail image is missing a ')' :P
@_lun4r_
@_lun4r_ Жыл бұрын
The thumbnail is missing a bracket You meant to do this instead: for i in range(len(data)): print(data[i])
@mienislav
@mienislav Жыл бұрын
5:36 Itertools are in many cases slower than normal loops. I don't recommend them!
@CrittiZops
@CrittiZops Жыл бұрын
What's your theme????
@djst3rling863
@djst3rling863 Жыл бұрын
shades of purple
@sleeplessmidnight779
@sleeplessmidnight779 Жыл бұрын
but bts, sum must be using for loop too, isn't it?
@DendrocnideMoroides
@DendrocnideMoroides Жыл бұрын
yes but it is implemented in C which is way faster
@sleeplessmidnight779
@sleeplessmidnight779 Жыл бұрын
@@DendrocnideMoroides thanks bro, could you please explain why python is slow as compared to c, is it because python use interpreter ?
@DendrocnideMoroides
@DendrocnideMoroides Жыл бұрын
​@@sleeplessmidnight779 there are 2 main reasons why python is slower than C (and most other programming languages) (yes that fact that python is interpreted also slows it down but that is not one of the main reasons) Biggest Reason: it is dynamically-typed meaning that if you create a variable that is of a certain type you can easily change its type afterward (For example if you write a=5 (which is an integer) and then you write a="Hello" (which is a string) python will accept that instead of throwing an error like statically-typed languages) this means python will always need to check the type of the variable before any operation this issue can be overcome by using CPython where you can specify the types variables, CPython is not quite as fast as pure C but still a good option because its syntax is very similar to that of python's, and in fact you do not need to specify the type of every variable but the more you specify the faster the code will become 2nd Biggest Reason: it has a "Global Interpreter Lock" which means python can only use one of the threads/cores of your computer while executing code (this is for safety reasons and exists because Python is dynamically-typed) this issue can be overcome by using multithreading but using multithreading is less safe and you should only do it if you know what you are doing
@djst3rling863
@djst3rling863 Жыл бұрын
There is no magical way to sum a list without enumerating it. However, not much can beat compiled C code, performance wise, which is what the built-in sum() function uses under-the-hood. It's generally at least 5x faster than a standard Python for loop.
@Hardcore_Remixer
@Hardcore_Remixer Жыл бұрын
Welp, may as well write my loop code in C/C++ and import it in python.
@djst3rling863
@djst3rling863 Жыл бұрын
No you shouldn't. This is exactly what Python's built-ins do for you. Use them.
@peabody3000
@peabody3000 Жыл бұрын
step 1: ask chatGPT step 2: copy step 3: paste
@V0W4N
@V0W4N Жыл бұрын
coding is one of the few activities where being lazy is actually helpful
@Maxiker21
@Maxiker21 Жыл бұрын
It is not true, that loops are bad, as they are the place that JIT compilers can shine after all. It is all just about the python implementation
@the_2663
@the_2663 Жыл бұрын
Why is it always "for i " and Not "for anything " that can be :-D
@jaykay7932
@jaykay7932 Жыл бұрын
No idea about python but in every instance where a for in loop can be used it’s a lot more efficient to use a traditional for loop
@francescoanastasio2021
@francescoanastasio2021 Жыл бұрын
“This is very error-prone”: why?
@djst3rling863
@djst3rling863 Жыл бұрын
1:00 I assume he means "enumerate" is more intuitive to use, since it avoids having to pass indices to arrays to retrieve values. I think he's right in this case. A lot of bugs live in for loops - especially near boundaries.
@lambrechta
@lambrechta Жыл бұрын
So it's great, but in the real world where you have just average programmers of various ages, things like "lambda" will look like black magic to them. May be efficient but difficult to support software like that in the IT shop.
@djtomoy
@djtomoy 7 ай бұрын
Some of these sound too confusing and harder too read
@IMDash_freak002
@IMDash_freak002 8 ай бұрын
😢
@benediktmaier6388
@benediktmaier6388 Жыл бұрын
Anything is better than your thumbnail code because that doesn’t even run
@joshuaworman4022
@joshuaworman4022 Жыл бұрын
i hate to be that guy. but it is impressive how bad python messed up how loops are implemented. when in other languages its just a goto. wonder why they did that. thank god for pypy.
@djst3rling863
@djst3rling863 Жыл бұрын
What you're looking at is just syntactic sugar. Recall that Python is a high level language which generally sits on top of C. Thus, it's all the same under-the-hood. Compile your Python to C and disassemble it. You'll see all of your familiar goto, cmp, jmp, etc. - statements.
@dsrawat6092
@dsrawat6092 Жыл бұрын
I am second
@gaxkiller
@gaxkiller Жыл бұрын
I really don't get why people love python, I have to use it daily at work since our backend is in python, and I have zero fun using it, I feel the language is not helping me, it is in my way
@djst3rling863
@djst3rling863 Жыл бұрын
What general purpose language(s) do you prefer?
@gaxkiller
@gaxkiller Жыл бұрын
@@djst3rling863 C#, rust, go, dart, kotlin, swift.
@antonpieper
@antonpieper Жыл бұрын
7th tip: just use another language like C or Java
@jdsahr
@jdsahr Жыл бұрын
You know, I get all these "use native methods" things in Python, but at what point does Python become less readable because there are all these little native functions? Wouldn't it be better to let an optimizer turn a for loop into a list comprehension? Just how, exactly, is a list comprehension *always* better than a for loop in terms of readability? Sure, it's better for speed, but is it better for readability? It would be an error if Python got turned into APL (a fabulous, but write-only language). ----- Fire is a good servant, but a bad master. Let us have computer languages which serve us, rather than having us serve them.
@andreypetrov2634
@andreypetrov2634 Жыл бұрын
Bad advise: "write more complex code, and another programmers will spend more and more time to understand your code".
@juanignaciobruzzone2896
@juanignaciobruzzone2896 Жыл бұрын
You know you are not avoiding loops right? under the hood it's still a loop. so even if you recommend using sum, you are getting around by using a buildin method, which still uses loops to acomplish the same result. This video is the definition of the stupidity going around about recommending stuff to people so they don't learn how things work. Yes, you are right, a personal made loop might be slower than the *super mega optimized built in method* but at least the poeple learn to do stuff on their own and not rely on everything being handed to them on a silver platter. Thanks for taking us into a sad future where people don't need to use brains.
@willygepe
@willygepe Жыл бұрын
It’s not only about run-time efficiency, but also code readability, maintainability and reduce the risk of introducing bugs. If you want to compute the sum of all values of a list, it is better to state exactly that on a single line that to create a custom loop, with local variables with no other purpose, and letting to the reader to identify the pattern.
@adrianbool4568
@adrianbool4568 Жыл бұрын
There is a massive difference in performance between a loop of Python bytecode instructions (which a Python for loop will result in) and pure C loop which, for example, the sum() function will use.
@juanignaciobruzzone2896
@juanignaciobruzzone2896 Жыл бұрын
@@adrianbool4568 i agree with what you say, however, you are still missing my point.
@adrianbool4568
@adrianbool4568 Жыл бұрын
@@juanignaciobruzzone2896 If your argument is that you want people to learn more; how can you argue against teaching people alternative (and often more efficient) ways to implement algoirthms beyond blindly repeating for loops all over the place?
@jankucera8505
@jankucera8505 Жыл бұрын
clickbait
@SnowCat6
@SnowCat6 Жыл бұрын
Питон это жуткий ущербный язык.
@shuflee2754
@shuflee2754 9 ай бұрын
Stick to the basics. Don't memorize useless stuffs.
@Jonx-dev
@Jonx-dev Жыл бұрын
just dont use python if you care about performance
@iWhacko
@iWhacko Жыл бұрын
the best way is not use python at all
@ericbroun4657
@ericbroun4657 Жыл бұрын
Top 10 Python One Liners YOU MUST KNOW!
4:52
Patrick Loeber
Рет қаралды 136 М.
11 Tips And Tricks To Write Better Python Code
11:00
Patrick Loeber
Рет қаралды 598 М.
OMG 😨 Era o tênis dela 🤬
00:19
Polar em português
Рет қаралды 3,7 МЛН
ХОТЯ БЫ КИНОДА 2 - официальный фильм
1:35:34
ХОТЯ БЫ В КИНО
Рет қаралды 1,5 МЛН
Don't eat centipede 🪱😂
00:19
Nadir Sailov
Рет қаралды 22 МЛН
5 Tips To Write Better Python Functions
15:59
Indently
Рет қаралды 74 М.
25 nooby Python habits you need to ditch
9:12
mCoding
Рет қаралды 1,7 МЛН
How To Use Pandas In Python
6:45
Taylor's Software Solutions
Рет қаралды 246
10 ULTIMATE Python Tips 🔥
16:42
Tech With Tim
Рет қаралды 60 М.
Introduction to For Loops in Python (Python Tutorial #5)
10:22
CS Dojo
Рет қаралды 1,6 МЛН
Stuck in Nested Loops? Here's How You Leave Them!
11:33
NeuralNine
Рет қаралды 7 М.
Python 101: Learn These 5 Must-Know HIDDEN Features
16:38
Tech With Tim
Рет қаралды 66 М.
10 Python Shortcuts You Need To Know
27:27
Tech With Tim
Рет қаралды 290 М.
Python For & While Loops for Data Science / Data Analysis - P.3
23:39
5 Useful Dunder Methods In Python
16:10
Indently
Рет қаралды 47 М.
OMG 😨 Era o tênis dela 🤬
00:19
Polar em português
Рет қаралды 3,7 МЛН