1. What are the key features of Python?
Python has a simple and easy-to-read syntax, dynamic typing, automatic memory management, a large standard library, and support for multiple programming paradigms.
2. Explain the difference between a list and a tuple.
Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable and cannot be modified after creation.
3. How do you comment in Python?
Single-line comments start with a hash symbol (#), while multi-line comments can be enclosed within triple quotes (”’ or “””).
4. What is a Python dictionary?
A dictionary is an unordered collection of key-value pairs, where each key is unique. It is also known as an associative array or hash map in other programming languages.
5. What is the purpose of the “self” keyword in Python?
The “self” keyword is used as a reference to the instance of a class. It is typically the first parameter of a method in a class definition.
6. How do you handle exceptions in Python?
Exceptions can be handled using try-except blocks. Code that may raise an exception is placed in the “try” block, and the handling code is written in the “except” block.
7. What is the difference between “range” and “xrange” in Python 2?
In Python 2, “range” returns a list, while “xrange” returns an iterable object. This helps save memory when working with large ranges.
8. Explain the difference between a shallow copy and a deep copy.
A shallow copy creates a new object with references to the original elements, while a deep copy creates a completely independent copy of the original object and its nested objects.
9. What is the purpose of the “if name == ‘main‘:” statement?
This statement allows code to be executed only when the script is run directly, not when it is imported as a module. It is commonly used for test code or script execution.
10. How do you handle file I/O in Python?
File I/O can be performed using the built-in functions “open()”, “read()”, “write()”, “close()”, as well as the context manager “with” statement for automatic resource cleanup.
11. What are lists and tuples? What is the key difference between the two?
Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets['sara', 6, 0.19]
, while tuples are represented with parantheses('ansh', 5, 0.97)
.
But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference:
my_tuple = ('sara', 6, 5, 0.97)
my_list = ['sara', 6, 5, 0.97]
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'sara'
my_tuple[0] = 'ansh' # modifying tuple => throws an error
my_list[0] = 'ansh' # modifying list => list modified
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'ansh'
12. What is pass in Python?
The pass
keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.
def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block
13. What is __init__?
__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. It helps in distinguishing methods and attributes of a class from local variables.
# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")
14. What are Keywords in Python?
Keywords in python are reserved words that have special meaning.They are generally used to define type of variables. Keywords cannot be used for variable or function names. There are following 33 keywords in python-
- And
- Or
- Not
- If
- Elif
- Else
- For
- While
- Break
- As
- Def
- Lambda
- Pass
- Return
- True
- False
- Try
- With
- Assert
- Class
- Continue
- Del
- Except
- Finally
- From
- Global
- Import
- In
- Is
- None
- Nonlocal
- Raise
- Yield
15. How is memory managed in Python?
Memory is managed in Python in the following ways:
- 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.
16. What is PYTHONPATH?
It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
17. Is indentation required in python?
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
18. How can you generate random numbers in Python?
Random module is the standard module that is used to generate a random number. The method is defined as:
import random
random.random
The statement random.random() method return the floating-point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are:
- randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object.
- uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
- normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.
- The Random class that is used and instantiated creates independent multiple random number generators.
19. What are docstrings in Python?
Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.
Example:
"""
Using docstring as a comment.
This code divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)
Output: 2.0
20. Whenever Python exits, why isn’t all the memory de-allocated?
- 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.
21. What does this mean: *args, **kwargs? And why would we use it?
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.
22. How can files be deleted in Python?
To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function.
Example:
import os
os.remove("xyz.txt")
23. How Python is interpreted?
- Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.
- Source code is a file with .py extension.
- Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called “bytecode”.
- .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy.
24. What is slicing in Python?
Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicing is-[start:end:step]
. The step can be omitted as well. When we write [start:end]
this returns all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or end element is negative i, it means the ith element from the end. The step indicates the jump or how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]
. Then [-1:2:2]
will return elements starting from the last element till the third element by printing every second element.i.e. [8,6,4]
.
25. How do you handle concurrency and parallelism in Python?
Concurrency and parallelism in Python can be handled using various modules and techniques such as the concurrent.futures
module, multiprocessing, threading, and asynchronous programming with asyncio
.
26. What is type conversion in Python?
Type conversion refers to the conversion of one data type into another.
int() – converts any data type into integer type
float() – converts any data type into float type
ord() – converts characters into integer
hex() – converts integers to hexadecimal
oct() – converts integer to octal
tuple() – This function is used to convert to a tuple.
set() – This function returns the type after converting to set.
list() – This function is used to convert any data type to a list type.
dict() – This function is used to convert a tuple of order (key, value) into a dictionary.
str() – Used to convert integer into a string.
complex(real,imag) – This function converts real numbers to complex(real,imag) number.
27. What is a lambda function?
An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
Example:
a = lambda x,y : x+y
print(a(5, 6))
Output: 11
28. What are negative indexes and why are they used?
The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.
The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.
29. How to remove values to a python array?
Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.
Example:
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
print(a.pop())
print(a.pop(3))
a.remove(1.1)
print(a)
Output:
4.6
3.1
array(‘d’, [2.2, 3.8, 3.7, 1.2])
30. Explain the concept of operator overloading in Python.
Operator overloading is a feature in Python that allows operators such as +
, -
, *
, /
, etc., to be defined and customized for user-defined classes. It enables objects to behave like built-in types.