Python (General) Flashcards

Based off https://www.edureka.co/blog/interview-questions/python-interview-questions/

1
Q

What are the key features of Python (name 5)?

A

Interpreted language: Unlike languages like C and its variants, Python does not need to be compiled before it is run.

Dynamically typed: 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.

Suited to OOP: Allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private).

Writing is quick but running is often slower than compiled languages: However, Python allows the inclusion of C-based extensions eg. NumPy’s number-crunching isn’t done in Python so it is fast

Functions and classes are first-class objects. This means that they can be assigned to variables, returned from other functions/classes and passed into functions/classes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Python is an interpreted language. Explain.

A

An interpreted language is any programming language which is not in machine-level code before runtime. Therefore, Python is an interpreted language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is PEP 8?

A

PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How is memory managed in Python (3 parts)?

A
  1. 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.
  2. 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.
  3. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is namespace in Python?

A

A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is PYTHONPATH?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are Python modules? Name some commonly used built-in modules in Python.

A

Python modules are files containing Python code. This code can either be functions, classes or variables. A Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:
os, sys, math, random, datetime, JSON

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is __init__?

A

__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a lambda function?

A

An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is self in Python?

A

Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional. It helps to differentiate between the methods and attributes of a class with local variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How does break, continue and pass work?

A

Break: Allows loop termination when some condition is met and the control is transferred to the next statement

Continue: Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop

Pass: Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you reverse the order of an array or sequence?

A

[::-1] or reverse()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between range & xrange?

A

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. If you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a generator in python? How do you create one?

A

A generator is a function used to create iterator objects. it returns an object that can only be used with the for-in loop or next() methods. We can use the yield keyword to create a generator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is pickling and unpickling?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are docstrings in Python?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are operators? What is the purpose of is, not and in operators?

A

Operators are special functions. They take one or more values and produce a corresponding result.

is: returns true when 2 operands are true (Example: “a” is ‘a’)
not: returns the inverse of the boolean value
in: checks if some element is present in some sequence

18
Q

Whenever Python exits, why isn’t all the memory de-allocated (3 reasons)?

A
  1. 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.
  2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
  3. On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.
19
Q

What is a dictionary in Python?

A

A dictionary defines a one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

20
Q

How can the ternary operators be used in Python? What is the syntax?

A

The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.

Syntax: [on_true] if [expression] else [on_false]

21
Q

What does this mean: *args, **kwargs? And why would we use it?

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.

22
Q

What are Python packages?

A

Python packages are namespaces containing multiple modules. They are also modules too; they just contain other modules with an __init__.py file.

23
Q

Explain split(), sub(), subn() methods of “re” module in Python.

A

To modify the strings, Python’s “re” module is providing 3 methods. They are:

split() – uses a regex pattern to “split” a given string into a list.

sub() – finds all substrings where the regex pattern matches and then replace them with a different string

subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

24
Q

What are the built-in types of python?

A
The principal built-in types are:
Text: str
Boolean: bool
Numerics: int, float, complex
Sequences: list, tuple, range
Mappings: dict
Set: set, frozenset
Binary: bytes, bytearray, memoryview
25
Q

What methods can we use to add to a Python array (name 3)?

A

Elements can be added to an array using the append(), extend() and the insert (i,x) functions:
Append: adds one element to end of array
Extend: adds a list of elements to end of array
Insert: adds an element to a specified position

26
Q

What methods can we use to remove from a Python array (name 2)?

A

Array elements can be removed using pop() or remove() method:
Pop: Removes the last element if no parameters, or the element at specified position
Remove: Removes a specified element

27
Q

What is the difference between deep and shallow copy?

A

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. The 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. 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.

28
Q

Explain Inheritance in Python and the types of inheritance (name 4).

A

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 sub-class.

Single inheritance: Enables a subclass or derived class to inherit properties and characteristics of the parent class

Multiple inheritance: Enables a child class to inherit from more than one parent class, not in Java

Multi-level inheritance: Transfer of the properties of characteristics is done to more than one class hierarchically, like a super-super-class

Hierarchical inheritance: Allows a class to host as a parent class for more than one sub-class

29
Q

What is polymorphism in Python?

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.

30
Q

Define encapsulation in Python.

A

It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.

31
Q

How do you do data abstraction in Python?

A

Data abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using abstract classes.

32
Q

What are the main features of OOP when used in Python?

A

Classes and objects, inheritance, encapsulation, polymorphism, abstraction

33
Q

What is a decorator in Python?

A

Decorators in Python add some feature or functionality to an existing function without altering it. They are implemented with the @ symbol, examples include classmethod and property in OOP

34
Q

What is an iterator in Python?

A

An iterator is an object that can be “traversed” through. In other words, it is an object that can be accessed in iterations in place of the full object.

In Python, an iterator is any object that implements the iterator protocol. The protocol contains two built-in functions (iter() and next()). A list is a built-in iterator in python.

35
Q

What are dict and list comprehensions? What is the syntax for both?

A

The comprehensions in Python are simple ways to create a new object from an existing object. There are several of these, including list, dict, set, and nested comprehensions.

Syntax for dict comprehension: dict_name = {key: value for (key, value) in oldDict.items()}

Syntax for list comprehension: list_name = [expression for variable in old_list condition]

36
Q

What is scope in Python?

A

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. Examples include local, global, module-level and outermost scope.

37
Q

Why do we do modular programming in Python (4 reasons)?

A

Simplicity: Working on a single module helps you focus on a small part of the problem, making development easier and less error-prone

Maintainability: Modules are written in a manner that reduces interdependency, meaning it is less likely that modifications in a module might impact other parts of the program

Reusability: Functions defined in a module can be easily reused by other parts of the application.

Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program

38
Q

What is slicing in Python?

A

Slicing is taking parts of strings, arrays, lists or tuples. The syntax for slicing is [start : stop : step], where start is the starting index from where to slice, stop is the ending index, and step is the number of steps to jump.

39
Q

Can you name five built-in functions in Python and explain briefly?

A

eval(): Parses a string as an expression

input(): Reads and returns a line of string

len(): Returns the length of an object

open(): Opens a file

format(): Format a string

40
Q

How do you show protected and private variables?

A

Python does not have access modifiers unlike Java, however to imitate the convention is to prefix a protected member with a single underscore and a private with double underscore.