Explain all file processing modes supported in Python?
Python has various file processing modes.
For opening files, there are three modes:
πread-only mode (r)
πwrite-only mode (w)
πreadβwrite mode (rw)
For opening a text file using the above modes, we will have to append βtβ with them as follows:
πread-only mode (rt)
πwrite-only mode (wt)
πreadβwrite mode (rwt)
Similarly, a binary file can be opened by appending βbβ with them as follows:
πread-only mode (rb)
πwrite-only mode (wb)
πreadβwrite mode (rwb)
To append the content in the files, we can use the append mode (a):
For text files, the mode would be βatβ
For binary files, it would be βabβ
Share and Support
@Python_Codes
Python has various file processing modes.
For opening files, there are three modes:
πread-only mode (r)
πwrite-only mode (w)
πreadβwrite mode (rw)
For opening a text file using the above modes, we will have to append βtβ with them as follows:
πread-only mode (rt)
πwrite-only mode (wt)
πreadβwrite mode (rwt)
Similarly, a binary file can be opened by appending βbβ with them as follows:
πread-only mode (rb)
πwrite-only mode (wb)
πreadβwrite mode (rwb)
To append the content in the files, we can use the append mode (a):
For text files, the mode would be βatβ
For binary files, it would be βabβ
Share and Support
@Python_Codes
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