Python Codes
Kanalga Telegramāda oātish
This channel will serve you all the codes and programs which are related to Python. We post the codes from the beginner level to advanced level.
Ko'proq ko'rsatish7 090
Obunachilar
Ma'lumot yo'q24 soatlar
Ma'lumot yo'q7 kunlar
Ma'lumot yo'q30 kunlar
Postlar arxiv
7 090
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
7 090
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
7 090
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:
Mylist = [1,2,3] if(l := len(mylist) > 2) print(l)Output 3 Share and Support @Python_Codes
7 090
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:
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_Codes7 090
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
7 090
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
7 090
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:
Class A:
def func(self):
print(āHiā)
Share and Support
@Python_Codes7 090
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:
l = lambda x,y : x*y print(a(5, 6))Output:30 Share and Support @Python_Codes
7 090
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
7 090
What is a map function in Python?
The map() function in Python has two parameters, function and iterable. The map() function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results.
Example:
def calculateSq(n):
return n*n
numbers = (2, 3, 4, 5)
result = map( calculateSq, numbers)
print(result)
Share and Support
@Python_Codes7 090
Explain split(), sub(), subn() methods of āreā module in Python?
These methods belong to the Python RegEx or āreā module and are used to modify strings.
šsplit(): This method is used to split a given string into a list.
šsub(): This method is used to find a substring where a regex pattern matches, and then it replaces the matched substring with a different string.
šsubn(): This method is similar to the sub() method, but it returns the new string, along with the number of replacements.
Share and Support
@Python_Codes
7 090
What are the common built-in data types in Python?
Python supports the below-mentioned built-in data types:
Immutable data types:
šNumber
šString
šTuple
Mutable data types:
šList
šDictionary
šset
Share and Support
@Python_Codes
7 090
What is __init__ in Python?
šEquivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.
Syntax
class Human:
# init method or constructor
def __init__(self, age):
self.age = age
# Sample Method
def say(self):
print('Hello, my age is', self.age)
h= Human(22)
h.say()
Output:
Hello, my age is 22
Share and Support
@Python_Codes7 090
What is scope resolution?
š A scope is a block of code where an object in Python remains relevant.Each and every object of python functions within its respective scope.As Namespaces uniquely identify all the objects inside a program but these namespaces also have a scope defined for them where you could use their objects without any prefix. It defines the accessibility and the lifetime of a variable.
Letās have a look on scope created as the time of code execution:
šA local scope refers to the local objects included in the current function.
šA global scope refers to the objects that are available throughout execution of the code.
šA module-level scope refers to the global objects that are associated with the current module in the program.
šAn outermost scope refers to all the available built-in names callable in the program.
Share and Support
@Python_Codes
7 090
Inheritance in Python with an example?
šAs Python follows an object-oriented programming paradigm, classes in Python have the ability to inherit the properties of another class. This process is known as inheritance. Inheritance provides the code reusability feature. The class that is being inherited is called a superclass or the parent class, and the class that inherits the superclass is called a derived or child class. The following types of inheritance are supported in Python:
šSingle inheritance: When a class inherits only one superclass
šMultiple inheritance: When a class inherits multiple superclasses
šMultilevel inheritance: When a class inherits a superclass, and then another class inherits this derived class forming a āparent, child, and grandchildā class structure
šHierarchical inheritance: When one superclass is inherited by multiple derived classes
Share and Support
@Python_Codes
7 090
What are python namespaces?
šA Python namespace ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with āname as keyā mapped to its respective āobject as valueā.
Letās explore some examples of namespaces:
šLocal Namespace consists of local names inside a function. It is temporarily created for a function call and gets cleared once the function returns.
šGlobal Namespace consists of names from various imported modules/packages that are being used in the ongoing project. It is created once the package is imported into the script and survives till the execution of the script.
šBuilt-in Namespace consists of built-in functions of core Python and dedicated built-in names for various types of exceptions.
Share and Support
@Python_Codes
7 090
If you want to learn python
Try this 100 days of python
From basics to Advance course
Available in this channel for free
https://t.me/Python_100_Days_of_Code
