All 71 built-in Python functions
Skills:
RAG Basics80%
Key Takeaways
The video covers all 71 built-in Python functions, including math utilities, collections, strings, bytes, sets, frozen sets, iteration, lazy iteration, list comprehensions, async iteration, object inspection, modification, type checking, inheritance, method resolution order, descriptors, and dynamic features like eval, exec, and compile. Specific tools and functions mentioned include bytes, set, frozenset, bytearray, string, memoryview, open, ord, chr, bin, iter, enumerate, zip, reversed, sorted
Full Transcript
hey everyone let's go over all 71 built-in python functions well technically some of them aren't functions some of them are types like buou but these are the things that you don't have to install you don't even have to import them they're just Global names that are available that you can call so whether you're brand new to Python and just want to see what's available or you're more of an intermediate and just need a refresher on memory view let's get going first up we have math built-ins I'm talking about types like bu int float and complex as well as the math utilities Max Min divmod ABS pal round and sum bu is the built-in type whose only values are true and false when you use it like a function its purpose is to convert a value to true or false for instances of your own classes you can Define what bu does by defining a Dunder bu method next up we have int the built-in integer type when you use it as a function its purpose is to convert its argument like this string 123 into an integer 1 2 3 for your classes you can Define what it means to convert to an integer by defining a Dunder function next up float which is just like int but for floating Point numbers you can Define how your own classes convert to float with thunder float then we come to complex Python's built-in complex number type this does the exact same thing as using Python's built-in complex literal and note python uses the letter J for the imaginary unit for your own types you can use Dunder complex to Define how to convert to a complex number and on to the functions first up we have Max and Min given something like this list of numbers Max will give you the largest number and min will give you the smallest one it works with tupal sets dictionaries or any iterable instead of using an iterable you can also use the multi-argument forms when you have a fixed number of arguments next up we have div mod if you're ever doing a calculation where you're separately Computing the quotient and remainder you can do so more efficiently by using div mod then we have abs which gives you the absolute value of a number and for complex numbers it gives you the magnitude which is the distance to the origin you can define a Dunder ABS to customize what ABS does for your types next up we have pow which does the same thing as the built-in power operator pow also takes an optional third argument for the modulus this does the exact same thing as taking 2 to the^ 3 and then taking that Mod Five this turns out to be much more efficient if your exponent is really big and you guessed it you can customize pal for your own classes using Dunder pow next up round which can be used to round to a certain number of decimal places but be careful due to floating Point rounding errors rounding using python may not give you the same answer as rounding like you learned in school you can also round to a negative number of places to clear out lower powers of 10 and of course use dound to customize what round does for your classes then we have some which can be used to add up elements in an arbitrary iter it's also commonly used to count occurrences of how many elements satisfy some predicate by summing one for all the things that match some condition you can customize some by customizing what plus does using Dunder ad and that does it for math on to collections I'm talking about dict list tupal set and Frozen set all of these are types not functions dict creates a built-in dictionary type more commonly you would do this with the dictionary literal syntax though next up is list which is used to convert something into a list tupal are just like lists except you cannot modify them the benefit of doing this of course is that tupal can be used in sets and as keys of dictionaries whereas lists cannot set is used to create an instance of the built-in set type the typical reason for doing so is of course to remove duplicates you can also create a set with the built-in set literal syntax Frozen sets on the other hand have no literal syntax a frozen set is just like a set except it can't be mutated similar to how a tupal is just like a list but it can't be mutated moving on to our third category functions that have to do with strings and byes this includes the types byes bite array string and memory view as well as open CH or bin o hex format input asky and repper first up is byes that's used to construct the bytes object which can also be constructed using the literal byes syntax a byes object acts a lot like a tupal of integers between 0 and 255 however because of their primary use case byes also contain many convenience functions that make them act like strings or to convert to INF from strings next up we have the bite array type which is just like bytes except it's mutable then we come to good old string this is Python's built-in string type you use it as a function to convert anything to a string unlike in some lower level languages python on string type assumes that you're using Unicode encoding that's why in Python it's perfectly fine to paste a literal smiley face into your code and now we come to memory view one that I think a lot of you have probably never used before the memory view type is Python's way of allowing you to access raw bites as if it was a multi-dimensional array here we're supplying the raw bites by hand but more often this is used by a c extension type using the buffer protocol in this case the bytes represent four integers 1 2 3 4 we pass it to memory View and use cast to tell python that these should be treated as integers with a 2X two shape from then on we can use the memory view as if it's a 2x2 array next we have open which of course opens a file for reading or writing depending on the parameters you pass in of course we should prefer to use open with a width statement so that the file is automatically closed when we leave the wi block next up we have the pair of inverse functions Cher and or Cher takes an integer and gives you the corresponding asky character then or does the opposite it takes the character and gives you back the integer and technically we're not limited to asky here we can use any Unicode code point then we have bin OCT and hex which are convenience functions to give you string representations of a number in that certain format either binary octal or heximal you can actually reverse this operation and get the integer 42 back by passing in the base that was used in the string representation as the second argument to the built-in int next up we have format which is a little bit of a tricky one it's related but not quite the same as the do format method on on a string or more commonly F strings instead of just putting a variable here I can actually put a format specifier afterwards for instance colon X after the age will cause it to print out in heximal instead of decimal well the built-in format function is what does that conversion format of 31 gives the string 31 but format of 31 with the format specifier X gives 1f if you want to Define how this works for your own types which will work with format as well as with these format specifiers inside F strings and format then Define a Dunder format function to create format specs for your own types next up the built-in input function this pauses your program and waits for the user to enter input at the terminal and when they hit enter you get back whatever they typed as a string next up asky and repper the original idea behind repper was that if you typed in the string that repper returns then that would give you something equivalent to the original object but in modern day it's kind of just a more verose string conversion aski does the same thing it just calls ER but it ensures that the output only uses asky characters by escaping if necessary and that brings us to all the functions that have to do with iteration we've got iter next enumerate zip reversed sorted filter map all any range slice and the async ones a iter and aex iter takes any iterable like a list and it returns an iterator where an iterator is just something that you can call next on each time you call next it gives you the next element of the iteration a regular old for Loop in Python is the normal way you use them under the hood it calls iter a next for you and then we have a numerate which allows you to get the index of each item as you iterate over them so if I start with red green blue then when I iterate I'll get pairs zero red one green two blue but the normal way that you would use this is just in a for Loop where you destructure the index and the thing as you Loop over them zip on the other hand allows you to Loop over corresponding elements from different collections so if I zip together 1 2 3 and ABC then I'll get out 1 a 2 B 3 C and of course the normal way that you would use this is just by immediately destructuring the elements in a for Loop and then we have reversed which allows you to Loop over a sequence in reverse order you can customize What reversed means for your class with thunder reversed and here's an unexpected tidbit reversed actually works on a dictionary so in addition to the first element which is easy to get you can also access the last element efficiently and then there's sorted it returns a sorted copy of whatever you pass in the result of sorted is always a list though no matter what you pass in then we have filter which can be used to skip certain elements depending on whether or not they satisfy a certain condition in this case we take the numbers 1 to 10 and the condition we give is this function that checks the number is even for efficiency filter doesn't return a list you can iterate over it without ever making this list copy personally though I much prefer using a list comprehension with a guard Clause instead of using filter map on the other hand applies its function to each element so if if we start with 1 2 3 4 5 and give it this Lambda which squares a single element then we get the squares 1 49 16 25 once again we had to manually convert this to a list because map is Lazy by default and once again I much prefer using a list comprehension as a more readable alternative next up we have all and any both of these take in an iterable and tell you whether all or any of the elements in the iterable are truthy it's pretty intuitive except you do need to get used to what happens in the empty case all of nothing is true but any of nothing is false and that brings us to hopefully a very familiar one range a range represents all the numbers in a given range of course the normal way that you use a range is just by immediately looping over it in a for Loop and note that like many other iteration Tools in Python ranges are lazy and then we come to slice which is something that you would rarely ever actually type out but you do use pretty often this one colon 4 is kind of like using a slice literal except it's not really a slice literal you can't assign a variable to one colon 4 the way this would typically get used is when you're defining your get item inside of a class you can check if the item that you got was a slice and then do something different in that case and just like the literal syntax you can also provide a step parameter to slice as well and that brings us to async iteration a iter and aex it's totally analogous to iter and next you call a itter on something in order to get an asynchronous iterator to it and the only thing you can do with an asynchronous iterator is call await a next on it each time you await a next you get the next element of the iterator and just like normal iterators you don't normally call a it or a next instead it all happens automatically when you do an async for loop our next category is debugging and interactivity just three things here breakpoint help and print calling breakpoint will pause the Python program and drop you into a debugger now this is going to be a command line debugger so I wouldn't recommend it unless you really need to do this your ID e probably has a much better gooey debugger built in that you don't have to modify your code in order to use help um prints out help text and print I can't imagine you don't know this one if you made it this far into the video but at the very least maybe you didn't know that print has a file parameter anyway moving on to our next category object inspection and modification here we have the base object type all the adders get Adder set Adder Dell Adder has Adder we have dur ID # length his instance is subclass callable and super and type you can't do much with a base object instance but there is one common use case and that's using an object as a sentinel the only purpose of a sentinel is that you can check whether something is or is not the Sentinel if I didn't care too much I could just use get with no default parameter and then check if the value that I get is none and that would indicate that the value wasn't in the map but maybe none is a meaningful value for me and I want to know whether I got none in the map or whether it wasn't in the map in that case I can use the Sentinel as the default value and then if the value that I got back is the Sentinel then the value wasn't in there this Sentinel trick can be used anytime you need a value that is guaranteed to have never been used before you just created it so there's no way anybody else is using it and that brings us to get Adder set Adder D adder and has Adder let's say we define a class that has some attribute and we create an instance of the class of course I can access the value of the attribute by saying instance attribute but doing it this way I have to know attribute ahead of time what if I wanted to use a variable to determine which attribute to look up instead of always looking up attribute well that's exactly what get Adder does here I've typed in attribute but that could have been a variable and just like get on a dictionary get Adder can also be used with a default set Adder is a similar story I can say instance. new attribute and give it a value if I want to use a variable to determine which attribute to set then instead I can use set Adder then if I want to check if an instance has a certain attribute of course that's what has Adder does and Dell Adder is the equivalent for deleting attributes another way that you can check what attributes are available is using dur now dur is very much meant to be a convenience function it is not guaranteed to be correct or complete for that reason I basically never use it but in theory it could be useful for some kind of type that laily generates attributes as you ask for them next up we've got ID which tells you the unique identity of an object every object in Python is given a number that uniquely differentiates it from all other objects in Python it could be reused after the object dies but as long as the object is alive that number remains stable and you can use it to check whether an object is the same as some other object for instance we can determine that this hello is literally The Identical object as this Hello by comparing their identities and seeing they're equal whereas if I create two sets that both contain 1 2 3 yes they're equal but no they are not literally the same object normally though if you just wanted to know whether or not two things are the same object you would use the is or is not operator under the hood is and is not just compare the IDS but sometimes it can be useful to keep track of objects by their ID for instance if you're traversing a graph of nodes you can keep track of which ones you've already seen by keeping a set of the IDS the hash builtin gives you the hash of an object it's an integer that's used in hashtable or hash set based implementations of dictionaries or sets I'm definitely not going to do justice to the idea of a hash table in this video but suffice it to say that using hashes allows you to look up a single object in a huge collection without traversing the entire collection uh length tells you the length and then we have is instance and is subass now every object in Python has a type and unlike some languages you can actually access that type information at runtime you can say if someone gives me an INT do one thing if someone gives me a string do something else but your first instinct of using type and checking whether you get a particular value is probably not what you want in most cases your code should operate the same if someone passes a subass instead of the parent class what is instance literally does is look at the method resolution order of the value and check if int is in it so this check will pass if value is an INT or a subass of an INT or a subass of a subass of an INT and so on and fun fact in Python booleans are integers a subass does something completely analogous to is instance but it operates on the classes themselves not on instances then we have callable which tells you whether something is or isn't a callable in Python functions are callables classes are callables methods are callables but a string is not callable next we have super super actually returns a proxy object that when you access one of its attributes it looks up the attribute from whoever is next in line in the object's method resolution order that can be really complex if you using multiple inheritance but for single inheritance that just means grab this from my parent class and the last one in this group is type which actually has two separate uses the first we've already seen type of some object tells you what the type of the object is but type can actually be used in a completely separate way which is to create a new type give it a name its base classes and its class dictionary and python will dynamically create a new type that has those parameters this is definitely not the normal way to create a type the normal way is to use the class keyword then we come to the three descriptors class method property and static method now these are the sneakiest ones because you don't normally call them with open close pen you normally use them as decorators let's talk about property first it's what allows you to quote own the dot in Python what that means is that in Python when you say instance. value you can actually change what that means because in this case value is a property it calls this function this Setter here allows me to then control what instance. Val equals something does the next two are very similar class method and static method class method and static method both allow you to call the method on either an instance or the class itself if you used Class method then python will automatically provide the class as the first argument whereas if you used static method then it won't provide a class argument the main difference of why you would choose one over the other is what you want to happen if someone inherits from this class if someone inherits from my class and they call this class method the value for class will be the child class whereas in the static method I don't have access to the class that this was called from so if I wanted to access other class attributes or call other class functions I would have to do so by name which is going to use the parent classes Behavior or the parent class's attribute even if this was being called from a child class and finally we come to the last category Dynamic features these things are extremely powerful usually not what you want and very easy to misuse I'm talking about eval exec compile globals locals vs and Dunder import eval takes a string representation of an expression and evaluates it as code this string contains the variable X and there's this variable X that's in our current scope so when we evaluate the expression that value of x is used and next up is a very similar flavored one exec eval evaluated and returned a single expression exec on the other hand can run multiple statements and it doesn't return anything the first step of exec a string is to compile it first so if you are exec something many times you might want to pre-compile it by using compile then we have globals which gives you access to the global module dictionary the return value is the real dictionary that the current module is using for its globals so if you modify it in the dictionary it actually changes real Global variables locals gives you a dictionary of all of the local variables in the current function but unlike you're not allowed to modify it then we have vars which gives you the underlying Dunder dict of an object and very last we have another one that you probably shouldn't be using Dunder import if I Dunder import math then the result is the real math module I can call math. sare root on 16 and get four however Dunder import has all kinds of extra options that you probably don't want to mess with for instance this one is like doing a from spam. Ham import eggs and sausage typically when when you're importing you just use the import statement of course but even in the case where the module that you might want to be importing comes from a variable if all you want to do is import the module then you should much prefer to use import lib basically it's just a much more userfriendly harder to mess up version than Dunder import and that's it that's all of them so let me know down below how many of them you already knew about and which one's your favorite thanks for watching and thank you to my patrons and donors for their support see you in the next one
Original Description
How many did you know?
A quick rundown of EVERY single one of the 71 builtin Python functions. Technically, these are not all functions, but these are the 71 callables that are listed in the Python docs as "Builtin functions". These are the global names that are available to call that you don't need to install or even import anything to use.
― mCoding with James Murphy (https://mcoding.io)
Docs: https://docs.python.org/3/library/functions.html
Source code: https://github.com/mCodingLLC/VideosSampleCode
SUPPORT ME ⭐
---------------------------------------------------
Sign up on Patreon to get your donor role and early access to videos!
https://patreon.com/mCoding
Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)
https://www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJHEE
Want to donate crypto? Check out the rest of my supported donations on my website!
https://mcoding.io/donate
Top patrons and donors: Laura M, Jameson, Dragos C, Vahnekie, Neel R, Matt R, Johan A, Casey G, Mark M, Mutual Information, Pi
BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Discord: https://discord.gg/Ye9yJtZQuN
Github: https://github.com/mCodingLLC/
Reddit: https://www.reddit.com/r/mCoding/
Facebook: https://www.facebook.com/james.mcoding
CHAPTERS
---------------------------------------------------
0:00 Intro
0:24 Math - bool int float complex max min divmod abs pow round sum
2:56 Collections - dict list tuple set frozenset
3:44 Strings - bytes bytearray str memoryview open
5:18 Strings - chr ord bin oct hex format input ascii repr
7:04 Iteration - iter next enumerate zip reversed sorted filter map
9:17 Iteration - all any range slice aiter anext
10:42 Debugging - breakpoint help print
11:16 Object - object getattr setattr delattr hasattr dir id
14:19 Object - hash len isinstance issubclass callable super type
16:29 Descriptors - property classmethod staticmethod
17:49 Dynamic - eval exec compile globals locals va
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from mCoding · mCoding · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Goodbye, List! Type hinting standard collections - New in Python 3.9
mCoding
Python's comma equals ,= operator?
mCoding
Finding Primes in Python with the Sieve of Eratosthenes
mCoding
Find the First Missing Positive Int | Hard Interview Question on LeetCode
mCoding
JSON Tutorial Python | Basic Python Recipes
mCoding
Simulating Brownian Motion in Python
mCoding
The Single Most Useful Decorator in Python
mCoding
The Fastest Way to Loop in Python - An Unfortunate Truth
mCoding
Numpy Array Broadcasting In Python Explained
mCoding
Brownian Motion Single Path Zoom
mCoding
Brownian Motion Fractal Zoom
mCoding
Magic Methods - Making Python builtins work with your classes
mCoding
50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
mCoding
The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
mCoding
How Fast is Python's Sort? Performance Testing
mCoding
C++ First Missing Int, faster than 100%!
mCoding
[April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
mCoding
Python dataclasses will save you HOURS, also featuring attrs
mCoding
C++ Sudoku Solver in 7 minutes using Recursive Backtracking
mCoding
Every PROOF you've seen that .999... = 1 is WRONG
mCoding
Python's sharpest corner is ... plus equals? (+=)
mCoding
Binary Search - A Different Perspective | Python Algorithms
mCoding
The Best Way to Check for Optional Arguments in Python
mCoding
Local and Global Variable Lookup Weirdness in Python
mCoding
Efficient Exponentiation
mCoding
How To Install Python for Data Science
mCoding
0.1 + 0.2 is NOT 0.3 in Most Programming Languages
mCoding
Python 3.10's new type hinting features
mCoding
Python 3.10's Quality of Life improvements
mCoding
Introducing mZips! Python Zip and Zip Longest
mCoding
Match statement tips
mCoding
Using except: is a HUGE mistake
mCoding
Python + YouTube API | Automating descriptions
mCoding
Anaphones, phonetic anagrams
mCoding
Cracking passwords using ONLY response times | Secure Python
mCoding
Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
mCoding
Diagnose slow Python code. (Feat. async/await)
mCoding
Python MD5 implementation
mCoding
Salting, peppering, and hashing passwords
mCoding
x to bool conversion in Python, C++, and C
mCoding
You should put this in all your Python scripts | if __name__ == '__main__': ...
mCoding
Find the Skyline Problem with C++ Solution Explained
mCoding
The ONLY C keyword with no C++ equivalent
mCoding
Should you use "not not x" instead of "bool(x)" in Python? (NO!)
mCoding
Multiple Assignments in Python
mCoding
Why I don't like Python's chained comparisons
mCoding
Automated Testing in Python with pytest, tox, and GitHub Actions
mCoding
You can pip install directly from GitHub
mCoding
__new__ vs __init__ in Python
mCoding
Metaclasses in Python
mCoding
The easy way to keep your repos tidy.
mCoding
Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
mCoding
Python __slots__ and object layout explained
mCoding
C++ cache locality and branch predictability
mCoding
Avoiding import loops in Python
mCoding
25 nooby Python habits you need to ditch
mCoding
Python staticmethod and classmethod
mCoding
Building a Python app with Anvil to email me if my website goes down (includes paid features)
mCoding
31 nooby C++ habits you need to ditch
mCoding
Interviewing the creator of C++, Bjarne Stroustrup
mCoding
More on: RAG Basics
View skill →Related Reads
📰
📰
📰
📰
How I made a scroll-scrubbed video portfolio fast (Next.js 15 + GSAP + canvas)
Dev.to · Pratham Sharma
5 Reasons HTML Is About to Change Frontend Development
Medium · Programming
5 Reasons HTML Is About to Change Frontend Development
Medium · JavaScript
copilot browser tools make the frontend reviewable
Dev.to · Paulo Victor Leite Lima Gomes
Chapters (12)
Intro
0:24
Math - bool int float complex max min divmod abs pow round sum
2:56
Collections - dict list tuple set frozenset
3:44
Strings - bytes bytearray str memoryview open
5:18
Strings - chr ord bin oct hex format input ascii repr
7:04
Iteration - iter next enumerate zip reversed sorted filter map
9:17
Iteration - all any range slice aiter anext
10:42
Debugging - breakpoint help print
11:16
Object - object getattr setattr delattr hasattr dir id
14:19
Object - hash len isinstance issubclass callable super type
16:29
Descriptors - property classmethod staticmethod
17:49
Dynamic - eval exec compile globals locals va
🎓
Tutor Explanation
DeepCamp AI