What is the lambda function in Python?
A lambda function is an anonymous function (a function that does not have a name) in Python. To define anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name ‘lambda function’. Lambda functions can have any number of arguments but only one statement.
Example:
Share and Support
@Python_Codes
A lambda function is an anonymous function (a function that does not have a name) in Python. To define anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name ‘lambda function’. Lambda functions can have any number of arguments but only one statement.
Example:
l = lambda x,y : x*yOutput:30
print(a(5, 6))
Share and Support
@Python_Codes
What is self in Python?
Self is an object or an instance of a class. This is explicitly included as the first parameter in Python. On the other hand, in Java it is optional. It helps differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object, while in other methods, it refers to the object whose method was called.
Syntax:
@Python_Codes
Self is an object or an instance of a class. This is explicitly included as the first parameter in Python. On the other hand, in Java it is optional. It helps differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object, while in other methods, it refers to the object whose method was called.
Syntax:
Class A:
def func(self):
print(“Hi”)
Share and Support@Python_Codes
What is the difference between append() and extend() methods?
Both append() and extend() methods are methods used to add elements at the end of a list.
👉append(element): Adds the given element at the end of the list that called this append() method
👉extend(another-list): Adds the elements of another list at the end of the list that called this extend() method
Share and Support
@Python_Codes
Both append() and extend() methods are methods used to add elements at the end of a list.
👉append(element): Adds the given element at the end of the list that called this append() method
👉extend(another-list): Adds the elements of another list at the end of the list that called this extend() method
Share and Support
@Python_Codes
How is Multithreading achieved in Python?
👉Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.
👉Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
👉This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.
Share and Support
@Python_Codes
👉Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.
👉Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
👉This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.
Share and Support
@Python_Codes
Inverts a dictionary with non-unique hashable values.
👉Create a collections.defaultdict with list as the default value for each key.
👉Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().
👉Use dict() to convert the collections.defaultdict to a regular dictionary.
CODE:
ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages)
Output: { 10: ['Peter', 'Isabel'], 9: ['Anna'] }
Share and Support
@Python_Codes
👉Create a collections.defaultdict with list as the default value for each key.
👉Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().
👉Use dict() to convert the collections.defaultdict to a regular dictionary.
CODE:
from collections import defaultdict
def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)
Example:ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages)
Output: { 10: ['Peter', 'Isabel'], 9: ['Anna'] }
Share and Support
@Python_Codes
Walrus operator:
The Walrus or := operator is one of the latest additions to python 3.8.
It is an assignment operator that lets you assign value to a variable within an expression like conditional statements, loops, etc.
Example
If we want to check and print the length of a list:
3
Share and Support
@Python_Codes
The Walrus or := operator is one of the latest additions to python 3.8.
It is an assignment operator that lets you assign value to a variable within an expression like conditional statements, loops, etc.
Example
If we want to check and print the length of a list:
Mylist = [1,2,3]Output
if(l := len(mylist) > 2)
print(l)
3
Share and Support
@Python_Codes
What Is FastAPI?
FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints.
It has the following key features:
👉Fast to run: It offers very high performance, on par with NodeJS and Go, thanks to Starlette and pydantic.
👉Fast to code: It allows for significant increases in development speed.
👉Reduced number of bugs: It reduces the possibility for human-induced errors.
👉Intuitive: It offers great editor support, with completion everywhere and less time debugging.
👉Straightforward: It’s designed to be uncomplicated to use and learn, so you can spend less time reading documentation.
👉Short: It minimizes code duplication.
👉Robust: It provides production-ready code with automatic interactive documentation.
👉Standards-based: It’s based on the open standards for APIs, OpenAPI and JSON Schema.
You can use this instead of Django and Flask
Share and Support
@Python_Codes
FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints.
It has the following key features:
👉Fast to run: It offers very high performance, on par with NodeJS and Go, thanks to Starlette and pydantic.
👉Fast to code: It allows for significant increases in development speed.
👉Reduced number of bugs: It reduces the possibility for human-induced errors.
👉Intuitive: It offers great editor support, with completion everywhere and less time debugging.
👉Straightforward: It’s designed to be uncomplicated to use and learn, so you can spend less time reading documentation.
👉Short: It minimizes code duplication.
👉Robust: It provides production-ready code with automatic interactive documentation.
👉Standards-based: It’s based on the open standards for APIs, OpenAPI and JSON Schema.
You can use this instead of Django and Flask
Share and Support
@Python_Codes
Difference between list and tuple in python
🔸List is mutable ( you can modify the original list) and it's values are written in sqare brackets [ ]
🔸Tuple is immutable ( you can't modify it) and it's values are written in parentheses ( ) delimited by comma( , )
🔸To convert list to tuple - we use tuple() function
list1 = [1,2,3]
print(tuple(list1)) Output : (1,2,3)
🔸 For single element list
list1 = [1]
print(tuple(list1)) Output : (1, )
▪️a tuple is a tuple because of comma not because of parentheses
@Python_Codes
🔸List is mutable ( you can modify the original list) and it's values are written in sqare brackets [ ]
🔸Tuple is immutable ( you can't modify it) and it's values are written in parentheses ( ) delimited by comma( , )
🔸To convert list to tuple - we use tuple() function
list1 = [1,2,3]
print(tuple(list1)) Output : (1,2,3)
🔸 For single element list
list1 = [1]
print(tuple(list1)) Output : (1, )
▪️a tuple is a tuple because of comma not because of parentheses
@Python_Codes
To shuffle pandas DataFrame df
df = df.sample(frac=1, random_state=123).reset_index(drop=True)
Alternatively, you can use sklearn.utils.shuffle().
#pandas
@Python_Codes
(
in a reproducible way):df = df.sample(frac=1, random_state=123).reset_index(drop=True)
Alternatively, you can use sklearn.utils.shuffle().
#pandas
@Python_Codes
Do you know abou .strip()
From the above example you can see that it removed all the characters mentioned in .strip('comw.') and returns the remaining string
@Python_Codes
From the above example you can see that it removed all the characters mentioned in .strip('comw.') and returns the remaining string
@Python_Codes
Useful Pandas🐼 method you should definitely know
✅ head()
✅ info()
✅ fillna()
✅ melt()
✅ pivot()
✅ query()
✅ merge()
✅ assign()
✅ groupby()
✅ describe()
✅ sample()
✅ replace()
✅ rename()
@Python_Codes
✅ head()
✅ info()
✅ fillna()
✅ melt()
✅ pivot()
✅ query()
✅ merge()
✅ assign()
✅ groupby()
✅ describe()
✅ sample()
✅ replace()
✅ rename()
@Python_Codes
💡 Python Tip: Do you know Ellipsis(...) can be used as a placeholder in Python, just like a 𝘱𝘢𝘴𝘴 statement?
@Python_Codes
@Python_Codes
💡 Python Life Hack: Do you know you can copy the files from a computer to a mobile phone 📱 without any cable using Python 🐍 ?
@Python_Codes
@Python_Codes
Python Class Anatomy
Almost everything a Python class definition can contain summed up in one image :)
@Python_Codes
Almost everything a Python class definition can contain summed up in one image :)
@Python_Codes