A.
A.
The main difference is that the List is Mutable and Tuple is not(Immutable). For more detail check here .
A.
PEP 8 is Python Enhancement Proposal
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability. PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of recommendations.
For ex. according to the official Python documentation, an identifier can be of any length. PEP 8 suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says 'readability counts'. So, a very long identifier will violate PEP-8 and PEP-20.
A.
There may be times in our code when we haven't decided what to do yet, but we must type something for it to be syntactically correct. In such a case, we use the pass statement.
A.
To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter within a function, the change reflects in the calling function. This is its default behavior. However, when we pass literal arguments like strings, numbers, or tuples, they pass by value. This is because they are immutable.
A.
The with statement in Python ensures that cleanup code is executed when working with unmanaged resources by encapsulating common preparation and cleanup tasks. It may be used to open a file, do something, and then automatically close the file at the end. It may be used to open a database connection, do some processing, then automatically close the connection to ensure resources are closed and available for others. "with" will cleanup the resources even if an exception is thrown. This statement is like the using statement in C#. Consider you put some code in a try block, then in the finally block, you close any resources used. The with statement is like syntactic sugar for that.
The syntax of this control-flow structure is:
with expression [as variable]: ….with-block >>> with open('data.txt') as data:
A.
While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-independent bytecode. Hence, we can execute it on any platform that supports the .pyc format. Python automatically generates it to improve performance(in terms of load time, not speed).
A.
Dictionaries. Membership testing is faster in dict than in list. Python dictionaries use hash tables, this means that a lookup operation (e.g., if x in y) is O(1). A lookup operation in a list means that the entire list needs to be iterated, resulting in O(n) for a list of length n.
A.
Tuples are stored in a single block of memory. Tuples are immutalbe so, It doesn't require extraspace to store new objects. ... It is the reason creating a tuple is faster than List. It also explains the slight difference in indexing speed is faster than lists, because in tuples for indexing it follows fewer pointers.
A.
Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period.
lambda arguments: expression # Program to show the use of lambda functions double = lambda x: x * 2 print(double(5))
This function has no name. It returns a function object which is assigned to the identifier double. We can now call it as a normal function.
For more details check here .
A.
The map() function in Python takes in a function and a list. map function executes the function given as the first argument on all the elements of the iterable given as the second argument. The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.
new_list = list(map(lambda x: x * 2 , my_list))
A.
The filter() function in Python takes in a function and a list as arguments.
The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True.
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
A.
The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
zip() returns an iterator of tuples.
>>> list(zip(['a','b','c'],[1,2,3])) [(‘a’, 1), (‘b’, 2), (‘c’, 3)]
Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be lists.
>>> list(zip(('a','b','c'),(1,2,3))) [(‘a’, 1), (‘b’, 2), (‘c’, 3)]
A.
Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated for Python. All Python objects are stored in this heap, and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space. Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.
A.
A namespace in Python 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 a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:
Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.
Global Namespace includes names from various imported packages/modules that is being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.
Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.
A.
Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes or variables defined and implemented Just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.
A.
Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.
Protected attributes are attributes defined with a underscore prefixed to their identifier eg. _pro. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.
Private attributes are attributes with double underscore prefixed to their identifier eg. __pri. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.
A.
__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them.
A.
We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.
A.
The signature for the list comprehension is as follows:
[ expression(var) for var in iterable ]
A dictionary has the same syntax as was for the list comprehension but the difference is that it uses curly braces:
adict = {var:var**2 for var in range(10, 20)}
The syntax for generator expression matches with the list comprehension, but the difference is that it uses parenthesis:
( expression(var) for var in iterable )
A.
Self is a keyword in Python used to define an instance or an object of a class. In Python, it is explicitly used as the first paramter, unlike in Java where it is optional. It helps in disinguishing between the methods and attributes of a class from its local variables.
The self is a Python keyword which represents a variable that holds the instance of an object. In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.
A.
The enumerate() function is used to iterate through the sequence and retrieve the index position and it's corresponding value at the same time.
>>> for i,v in enumerate(['Python','Java','C++']):
print(i,v)
0 Python
1 Java
2 C++
>>>
A.
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
A.
Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.
A.
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
A.
Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.
A.
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
Consider the below example:
# myModule.py class MyClass: def fun(self): print("fun()")
We can then run the monkey-patch testing like this:
import myModule def monkey_fun(self): print("monkey_fun()") myModule.MyClass.fun = monkey_fun obj = myModule.MyClass() obj.fun()
The output will be as below:
monkey_fun()
As we can see, we did make some changes in the behavior of fun() in MyClass using the function we defined, monkey_fun(), outside of the module myModule.
A.
Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.
Let's try and build a generator for fibonacci numbers -
## generate fibonacci numbers upto n
>>> def fib(n):
p, q = 0, 1
while(p < n):
yield p
p, q = q, p + q
>>> x=fib(10)
>>> x.__next__()
0
>>> x.__next__()
1
>>> x.__next__()
1
>>> x.__next__()
2
>>> x.__next__()
3
>>> x.__next__()
5
>>> x.__next__()
8
>>> x.__next__()
Traceback (most recent call last):
File "", line 1, in
x.__next__()
StopIteration
>>> ## iterating using loop
>>> for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8
0
1
1
2
3
5
8
>>>