10 Python Basics You Should Know!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
10 python basics you should know before this video i honestly could only tell eight without googling let me know in the comments if you can beat this one how to remove elements from a list while looping over it first let me show you what not to do never loop over a list and remove elements at the same time this will lead to errors in this example we loop over a list and want to remove all even numbers for this we have a little helper function to determine if the number is even or not notice that the final result still has a 2 in it so this is not correct the mistake in this code is that we removed the element while looping over it so then all elements got shifted one place to the left and as a result we skipped one iteration the correct way to do this is to loop over a copy of the list notice the tiny difference here this is called list slicing so with this syntax we create a copy of the list and can therefore modify the original list another option is to just create a copy and put in all elements that do not meet the condition we can do this in one line with the list comprehension syntax now notice another tiny change that makes the copy process a little bit more efficient with this syntax we assign the values to the slice of a and therefore modify the list in place the result is the same but it's a little bit faster than assigning to the whole list the last option is to use filter false from iter tools the approach is the same but here we don't have to write the list comprehension ourselves also the other tools functions are very efficient so this is another good option you can keep in mind two what does if name equals equals main mean if you test functions or other code from your script in the same file it's good practice to put everything in a if name equals equals main guard statement this makes a difference for these two cases we run it as the main program with python filename.pi or we import the file in another file with import file name when the python interpreter reads a source file it does two things first it sets a few special variables like this d under name and then it executes all the code it finds in the file so now if you run the file with python food or pi the python interpreter sets the d under name variable as d under main so this part is executed and function a is called if we now have another file bar.pi where we import foo and now we run this file with pythonbar.pi then this file is our d under main and the full file has the name foo so this will just execute the code part from our bar file however let's say we forgot the guard statement now if we run bar.pi again it also executes all the code in foodpi when we import it so we see another print statement usually this is not what we wanted so it's recommended to keep the guard statement in your files when running code three how to check if a file or directory exists first of all instead of checking if the file exists it's perfectly fine to directly open it and wrap everything in a try except block this strategy is also known as easier to ask for forgiveness and permission and is a perfectly accepted python coding style if you don't want to raise an exception or you don't even need to open a file and just need to check if it exists you have different options the first way is using the different methods in os.path is file returns true for a valid file is dur returns true for a valid directory and exists returns true for a valid file or directory starting with python 3.4 you can also use the pathflip module it offers an object-oriented approach to work with file system paths and this is now my preferred way of dealing with files and directories you can create a path object like this and now you can use the different methods is file is there and exists on the path object four how to find the index of an item in a list to find the index you can simply use mylist.index it returns a zero based index in the list of the first item whose value is equal to x if there is no such item it raises a value error so in order to deal with possible exceptions you can wrap everything in a try except block and for example assign -1 to the index in case it's not there notice also that it only returns one index of the first match so if there are multiple items of the same value and you want to get all indices then you can do this with list comprehension where you loop over the whole list five how to execute a program or system command from python to run a command use the subprocess module in the standard library and call subprocess.run note that the command argument must be a list of strings and not one single string with a whole command another option is to use os.system this takes one single string as argument however subprocess dot run is more powerful and even the official documentation recommends to use subprocess over os.system to execute a child program in a new process use dot p open here again you must pass in a list of strings six how to merge two dictionaries python dictionaries have a dot update other function that updates the dictionary with the key value pairs from other overriding existing keys this however modifies the original dictionary in place instead of returning a new one to create a new dictionary with the merge key value pairs you can use different methods depending on which python version you use since python 3.9 you can use the neat syntax with a single vertical bar or pipe sign since python 3.5 you can also use this syntax which is known as dictionary unpacking and for lower versions you have to create a copy of one dictionary and then call the update function with the other one seven how to create a nested directory since python 3.5 the best and easiest way to create a nested directory is by using pathflip path make dur by setting parents to true any missing directories are created as needed and by setting exists ok to true an exception will be ignored if the file already exists otherwise a file exists error is thrown for older python versions os path make durs can be used together with os path exists but if you have a version of 3.5 or newer the recommended way now is to use the pathflip module 8. what's the difference between class method and static method in python you will find some methods decorated with add static method or add class method but what exactly will they do let's look at an example to show the difference we can create an instance of a software engineer and now we can call the class method on the instance or on the class itself the same is true for the static method we can call it on the instance or on the class this means that for these two methods we don't even need to create an instance now notice that the class method gets the class as first argument but when calling the function we don't pass it in this is done for us similar to the self-argument in instance methods since we have the class argument inside a class method we know about class variables so in this example we can access class.alias on the other hand in the static method we neither have information about self nor about the class so essentially we could just use a global function for this like so so you might ask why use a static method at all then and not just use a global function and yeah you could do that but sometimes it makes sense to put code into a class as static method because it logically belongs with the class so when calling it we immediately see that it belongs to software engineer because we always have to type software engineer before it in the programming language this is also known as namespace nine what's the difference between the store and the wrapper method in python both are special methods also known as the under methods that return strings for built-in classes these two methods are already implemented and it's good practice to implement them ourselves when creating a custom class but what's the difference when i summarize the official documentation these rules apply wrapper is the official string representation it should be unambiguous store is the informal string representation and should be human readable wrapper is also a fallback posture if store is missing and calling print uses stir so a good rule of thumb here is wrapper is for developers and stir is for customers so if we have a look at another example of the built-in datetime object we see that by printing it we use stir and it displays the datetime object in a clean date string while when using wrapper it also shows information about the module 10. how to concatenate two lists the simplest way to combine two lists is by just using the plus operator another alternative worth mentioning is this syntax that we can use since python 3.5 this is a more general way to unpack and combine items for example if b is a tuple for the plus operator we get an error because we can't use the plus for a list in the tuple however the unpacking syntax works for different types of iterables so this is fine here one more thing worth mentioning is that both ways only create a shallow copy this means that the copy is one level deep modifying on level one does not affect the other list so we won't notice the difference in this code but with nested objects modifying on level 2 or deeper does affect the other in this example we have a nested list after creating a new list c we modify an inner item of a and notice that c now has the same modification too i have a whole tutorial about shallow versus deep copying if you want to learn more about this alright and now that's it i hope you enjoyed these basics and if so then please hit like and consider subscribing and then i hope to see you in the next video bye
Info
Channel: Python Engineer
Views: 7,606
Rating: 4.9764242 out of 5
Keywords: Python
Id: _K30onxUn1Q
Channel Id: undefined
Length: 10min 8sec (608 seconds)
Published: Sun Aug 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.