Тёмный

6 Tips to write BETTER For Loops in Python 

Patrick Loeber
Подписаться 267 тыс.
Просмотров 245 тыс.
50% 1

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

Опубликовано:

 

1 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 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.
@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 )
@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 6 месяцев назад
@Bebtelovimab I see you don't need tips on being unfunny.
@Migoyan
@Migoyan 6 месяцев назад
@Bebtelovimab Ok bro, we understand you're a kid. Now you can resume your day.
@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. 🙂
@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
@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.
@fengjeremy7878
@fengjeremy7878 Год назад
Very useful! I have always been writing inefficient and unreadble codes since I don't know these advanded methods.
@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!
@NateROCKS112
@NateROCKS112 Год назад
3:38 note that, in the generator expression, you can use tuple unpacking as well.
@overwatch2944
@overwatch2944 Год назад
Useful tips, very good video! Keep 'em coming my friend!
@sanjaysaha1311
@sanjaysaha1311 Год назад
Pairwise & takewhile were new to me. Thanks!!
@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.
@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.
@shashankemani1609
@shashankemani1609 Год назад
These are amazing tips. Thanks so much!
@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.
@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!
@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.
@GATEPREP
@GATEPREP Год назад
Cool Tips, thanks for sharing, Patrick :)
@ChrisHalden007
@ChrisHalden007 Год назад
Great video. Very useful. Thanks
@vorpal22
@vorpal22 Год назад
Did not know about the strict parameter added to zip in Py3.10. Nice!
@__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
@leandromaxado
@leandromaxado Год назад
Ward for the 1:45 tip to use later at a exam program later. Thanks, great video.
@user-kq6mt8nk2p
@user-kq6mt8nk2p Год назад
Thank you Patrick.
@pattty847
@pattty847 Год назад
You really always share very valuable information.
@allezvenga7617
@allezvenga7617 Год назад
Thanks for your sharing
@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
@aciddev_
@aciddev_ 23 дня назад
best for loop → for (int i = 0; i < 10; i++)
@miguelvasquez9849
@miguelvasquez9849 Год назад
very interesting the itertools packages, i didnt know about it.
@CodeWithTomi
@CodeWithTomi Год назад
love your videos man
@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
@kychemclass5850
@kychemclass5850 Год назад
Nice. Thank you.
@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.
@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.
@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 😂
@X_x_kingfisher_x_X
@X_x_kingfisher_x_X Год назад
Short but so big Thanks.
@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?
@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
@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.
@agenticmark
@agenticmark 4 месяца назад
Great videos so far! (this is my third video of yours today)
@VaeV1ct1s
@VaeV1ct1s Год назад
What for should i use islice instead of [ : 5]?
@worldwrestling2513
@worldwrestling2513 Год назад
Please tell me which plugin did you use in the design
@shakils1921
@shakils1921 Год назад
Which VS code theme you are using?
@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.
@adekakz9794
@adekakz9794 Год назад
Can i use thi in for loops on Java? and, is it safety?
@theannoyingone110
@theannoyingone110 Год назад
Syntax error on line 1 in thumbnail 🤓 Also nice vid
@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
@40.50
@40.50 Год назад
I also like shades of purple 💜
@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.
@itsmaxim01
@itsmaxim01 Год назад
isn’t an out of range array index supposed to return undefined?
@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(...):
@saitejam3769
@saitejam3769 Год назад
Sir we want more python tips and tricks
@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....
@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
@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.
@ele6133
@ele6133 11 месяцев назад
Okay what is the vs code theme? Oh and good video, really helpful
@NikhilBhatt69
@NikhilBhatt69 8 месяцев назад
one dark pro i guess
@sj_8811
@sj_8811 5 месяцев назад
Does anyone know the vscode theme he is using?
@danibarack552
@danibarack552 Год назад
Why use islice(lines, 5) instead of lines[:5] ?
@LeeK301
@LeeK301 Год назад
I learned a lot from this vid; learned even more from the comments 🐍 💬
@code4l111
@code4l111 Год назад
Thanks for the tips, but tell us, what's your VS Code theme?
@sonoftroy8572
@sonoftroy8572 Год назад
I’ll just keep it simple and use foreach(array $list as $key => &value); loop in php
@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
@DK1PL
@DK1PL Год назад
What about recursion? p.s. It couldn’t be true that imperative language can't deal with loops or ? 🤔
@RozeFound
@RozeFound Год назад
You forgot range closing ')' in code in the thumbnail.
@vineethgk
@vineethgk Год назад
Which ide ia this? Vscode?
@djst3rling863
@djst3rling863 Год назад
Yes, VS Code w/ the "shades of purple" theme
@bokyunggg
@bokyunggg Год назад
Cool😊
@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.
@oriabnu1
@oriabnu1 Год назад
please write function code on cyber security and steganography
@__________________________6910
vs code theme name ?
@andreypetrov2634
@andreypetrov2634 Год назад
Bad advise: "write more complex code, and another programmers will spend more and more time to understand your code".
@mairacristian54
@mairacristian54 Год назад
the thumbnail image is missing a ')' :P
@mienislav
@mienislav Год назад
5:36 Itertools are in many cases slower than normal loops. I don't recommend them!
@_lun4r_
@_lun4r_ Год назад
The thumbnail is missing a bracket You meant to do this instead: for i in range(len(data)): print(data[i])
@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.
@CrittiZops
@CrittiZops Год назад
What's your theme????
@djst3rling863
@djst3rling863 Год назад
shades of purple
@V0W4N
@V0W4N Год назад
coding is one of the few activities where being lazy is actually helpful
@peabody3000
@peabody3000 Год назад
step 1: ask chatGPT step 2: copy step 3: paste
@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
@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.
@benediktmaier6388
@benediktmaier6388 Год назад
Anything is better than your thumbnail code because that doesn’t even run
@djtomoy
@djtomoy 7 месяцев назад
Some of these sound too confusing and harder too read
@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
@IMDash_freak002
@IMDash_freak002 8 месяцев назад
😢
@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.
@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.
@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.
@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.
@dsrawat6092
@dsrawat6092 Год назад
I am second
@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 Год назад
Далее
10 ULTIMATE Python Tips 🔥
16:42
Просмотров 60 тыс.
5 Tips To Write Better Python Functions
15:59
Просмотров 82 тыс.
ЭТО ВООБЩЕ НЕ БОЛЬНО !
00:15
Просмотров 368 тыс.
Arigato !! 😂
00:11
Просмотров 2,1 млн
UFC 302: Пресс-конференция
22:48
Просмотров 1,4 млн
5 Useful Dunder Methods In Python
16:10
Просмотров 49 тыс.
2D water magic
10:21
Просмотров 481 тыс.
11 Tips And Tricks To Write Better Python Code
11:00
Просмотров 599 тыс.
For loops in Python are easy 🔁
5:06
Просмотров 236 тыс.
5 Really Cool Python Functions
19:58
Просмотров 35 тыс.
Turn Python BLAZING FAST with these 6 secrets
5:01
Просмотров 31 тыс.
Compiled Python is FAST
12:57
Просмотров 88 тыс.
5 Mini Python Projects - For Beginners
1:41:08
Просмотров 2,7 млн
ЭТО ВООБЩЕ НЕ БОЛЬНО !
00:15
Просмотров 368 тыс.