6 Tips to write BETTER For Loops in Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone I'm Patrick and in this video I show you six tips how you can write better for Loops in Python these tips include some refactorings that you can apply right away to improve your code so we start with a few very beginner friendly tips and then also move on to some Advanced ones let's get started the first tip is to not use Loops at all so Loops are usually very slow so you want to avoid them if possible so you always should be on the lookout for built-in methods that you can use instead the easiest example is when we want to calculate the sum over a list then you don't want to write a for Loop but instead you can use the build in a sum method and sum over all the numbers this will give you the same result in just one line and if we run this then you see this is the same result and these built-in methods are always optimized so usually this is the better choice than a raw for Loop the second tip is to use enumerate when you need both the index and the value so you could say for index in range length and then access the value like this this works but this is very error prone so a better way is to use enumerate here and say enumerate and then the numbers this will return the index and the value as a tuple so you can immediately unpack this here and then do whatever you want so here we simply print this so this will give us the same result and you can also optionally say start equals and then use a different number and then the counting should start at this value so if you run this then you see the count start at one so use enumerate instead of range link the third tip is to use the zip function if you need to Loop over multiple lists or iterables at once here again you could say for index in range length and then use one of those lists and then access the indices here this will work but again this is very error prone so let's say the first list is longer now if we run this this will raise an index error list index out of range so a better way here is to use the built-in zip function and sip A and B this will give you the value of the first list and the value of the second list at once so now here we can print value 1 and value 2 and now this will again work and this will automatically stop at the shorter of those lists so sometimes it's still useful to have the error here so that you can catch bugs in your application so in order to see an error in this case you can use the argument strict equals true this is new since Python 3.10 and now this will raise an error if one of those lists is longer so here we can see value error sip argument 2 is sure that in argument one so you sip here instead of range length tip number four is to think lazy and use a a generator if it's possible this Builds on top of tip number one where we want to avoid for loops and replace them with built-in methods and now additionally we want to be on the lookout for generators that we can use so in this example we want to calculate how many minutes we studied and we Loop over different events so we say for event in events and then we check if event 0 equals equals learn so this is a tuple here and then we say minutes study plus equals event one which is the second item here and now we can print the minutes studied this works but again remember if you want to calculate the sum you can use the build in sum method and now in addition we use a generator so we refactor it like this we use a generator expression here that looks the same like a list comprehension but with parentheses so we say event 1 for event in events it if event 0 equals equals learn and now we can also assign this to a variable study time so this could make our code more readable and then we can put this generator expression into this sum function this works as well the same like with a list so we can say some study times and now print the minutes studied so if we run this you see this produces the same results but now the difference here is that this generator is evaluated lazily so at this moment where we declare this nothing happens but now if we put this into the function now the calculations begin and that's why we say our code is lazy so this works and this is much better than this the one thing where you want to be careful is if you do this a second time so now if we print the sum again then notice this is now zero so be very careful here because when we use a generator then the objects are consumed and this is why the next time we use this the sum is zero so be careful here and for this I want to give a shout out to a talk that I found on YouTube it's called a deeper look at iteration in Python by treyhana it's an awesome talk I put the link in the description if you want to check it out tip number five is to use the editor tools module more edit tools provides you with functions with iterators for efficient looping so it has a lot of cool functions I don't show you all of them I just want to show you three very cool examples that you can use to refactor your code the first one is the I slice function here we want to iterate over lines and if we reach line 5 then we break so we can refactor this for loop with the I slice method and say I slice lines until index five and then we can assign this to an object first five lines so again this can make our code more readable and then we can iterate over this and print this so this will give us the same result here again be careful if you iterate a second time then this will be empty because this was consumed so here again you can use a start and a stop index so if you do it like this then it will start at index one and you can also use a step argument so now it uses a step size of two so yeah this is very cool if you just need to iterate over slices the second function is the pairwise function if we have a look at the documentation we can see that pairwise returns successive overlapping pairs taken from the input iterable so if we do it manually we have to say for I and range length data and now we have to say length data minus one because we then Access Data I and Theta I plus one so now we can refactor this with pairwise by saying four pair in pair eyes and this will give us a tuple so we can access index 0 and index 1 and now this will again give us the same result and this one here is much more optimized and the third function I want to show you is the take while function so often we want to iterate over an iterable and if we reach a certain condition like in this one if the item is not greater than zero if it's negative then we stop and say break so we can easily refactor this with take while and say take while and it takes the predicate as first parameter and then the iterable as second one so here this is a function where we can use a Lambda in one line so we say Lambda x and x has to be greater or equal than zero this will give us an iterator and now we can say four item in items and print the item and then again this will give us the same result so yeah these functions are really cool and again if you want to have a look at the other ones then check out the documentation here and tip number six if speed is really important or you do a lot of Matrix multiplications and math operations then use numpy numpy provides functions for many linear algebra methods and Matrix multiplications in a vectorized way so instead of for example calculating the dot product with a for Loop we want to avoid the for Loop and simply call numpy Dot this will give you the same result and is much faster and it also has many functions that you can also find in Python for example the build in some function you also have a numpy equivalent with numpy sum and then the range with numpy arrange so first let's print only the result and see that you get the same result so this took a few moments so this is the same and now let's also time both versions and now if we run this and wait a few seconds then you see the numpy version is much faster the only drawback that we should be aware of is that in the case of numpy we copied this whole array into memory so this will need more memory but is much faster and yeah these are all the tips I wanted to show you let me know if you enjoyed this video and then I hope to see you in the next one bye
Info
Channel: Patrick Loeber
Views: 224,729
Rating: undefined out of 5
Keywords: Python
Id: RvvXo2-9bnE
Channel Id: undefined
Length: 9min 18sec (558 seconds)
Published: Sun Nov 27 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.