Python Questions
Q. What is the difference between list and tuples?
LIST vs TUPLES
LIST | TUPLES |
Lists are mutable i.e they can be edited. | Tuples are immutable (tuples are lists which can’t be edited). |
Lists are slower than tuples. | Tuples are faster than list. |
Syntax: list_1 = [10, ‘Chelsea’, 20] | Syntax: tup_1 = (10, ‘Chelsea’ , 20) |
Q. What are the key features of Python?
- Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
- Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like
x=111
and then x="I'm a string"
without error
- Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s
public
,private
), the justification for this point is given as “we are all adults here”
- In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
- Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The
numpy
package is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by Python
- Python finds use in many spheres – web applications, automation, scientific modelling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.
x=111
and then x="I'm a string"
without errorpublic
,private
), the justification for this point is given as “we are all adults here”numpy
package is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by PythonQ. What is the difference between deep and shallow copy?
Ans: Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.
Q. How is Multithreading achieved in Python?
Ans:
- Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
- Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
- This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
- All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.
Q. How is memory managed in Python
Ans:
- Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
- The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
- Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.
Q. Explain Inheritance in Python with an example.
Ans: Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.
They are different types of inheritance supported by Python:
- Single Inheritance – where a derived class acquires the members of a single super class.
- Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
- Hierarchical inheritance – from one base class you can inherit any number of child classes
- Multiple inheritance – a derived class is inherited from more than one base class.
Q. What is the usage of help() and dir() function in Python?
Ans: Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
- Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
- Dir() function: The dir() function is used to display the defined symbols.
Q. Whenever Python exits, why isn’t all the memory de-allocated?
Ans:
- Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.
- It is impossible to de-allocate those portions of memory that are reserved by the C library.
- On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.
Q. What is dictionary in Python?
Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.
Q. What is monkey patching in Python?
Ans: In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
Consider the below example:
1
2
3
4
# m.py
class
MyClass:
def
f(
self
):
print
"f()"
We can then run the monkey-patch testing like this:
1
2
3
4
5
6
7
import
m
def
monkey_f(
self
):
print
"monkey_f()"
m.MyClass.f
=
monkey_f
obj
=
m.MyClass()
obj.f()
The output will be as below:
monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.
1
2
3
4
| # m.py class MyClass: def f( self ): print "f()" |
1
2
3
4
5
6
7
| import m def monkey_f( self ): print "monkey_f()" m.MyClass.f = monkey_f obj = m.MyClass() obj.f() |
Q. What does this mean: *args
, **kwargs
? And why would we use it?
Ans: 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.
*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.
Q. What is the difference between range & xrange?
Q. What is the difference between range & xrange?
Ans: For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.
Q. What is pickling and unpickling?
Ans: Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
Q. When will the else part of try-except-else be executed?
The else part is executed when no exception occurs.
Q. When will the else part of try-except-else be executed?
The else part is executed when no exception occurs.
Q. What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable. (Python Enhancement Praposal.)
Q.How Python is interpreted?
Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
Q.What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
Q.How are arguments passed by value or by reference?
Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.
Q.What is Dict and List comprehensions are?
They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
Q.What are the built-in type does python provides?
There are mutable and Immutable types of Pythons built in types Mutable built-in types
- List
- Sets
- Dictionaries
Immutable built-in types
- Strings
- Numbers
- Tuples
Q.What is namespace in Python?
In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.
Q. What is lambda in Python?
It is a single expression anonymous function often used as inline function.
Q. Why lambda forms in python does not have statements?
A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
Q. What is pass in Python?
Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.
Q. In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like list.
Q. What is unittest in Python?
A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.
Q. In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
Q. What are generators in Python?
The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.
Q. What is lambda in Python?
It is a single expression anonymous function often used as inline function.
Q. Why lambda forms in python does not have statements?
A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
Q. What is pass in Python?
Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.
Q. In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like list.
Q. What is unittest in Python?
A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.
Q. In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
Q. What are generators in Python?
The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
Q. Explain the use of decorators.
Ans: Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.
Q. How can you share global variables across modules?
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
Q. Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
Script file's mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
Q. How can you share global variables across modules?
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
Q. Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
Script file's mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
Q. Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
Script file's mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
Q. What is map function in Python?
Q. What is map function in Python?
0 comments:
Post a Comment