Python is an interpreted language. It is compiled to bytecode (.pyc
) and then executed by the Python Virtual Machine (PVM).
list1 = [1, 2]
list2 = [3, 4]
result = list1 + list2 # [1, 2, 3, 4]
for
: Iterates over a sequence.while
: Loops while a condition is true.
import math
math.floor(4.7) # Output: 4
is
: Compares memory locations.==
: Compares values.
- Numeric:
int
,float
,complex
- Sequence:
list
,tuple
,range
- Text:
str
- Set:
set
,frozenset
- Mapping:
dict
- Boolean:
bool
- Binary:
bytes
,bytearray
,memoryview
- None:
NoneType
A special constructor method to initialize object properties.
Feature | list | array (array module) |
---|---|---|
Types | Mixed types | Single data type only |
Flexibility | High | Optimized for numbers |
An environment variable that specifies where Python looks for modules.
A concise way to create lists:
[x*x for x in range(5)] # [0, 1, 4, 9, 16]
list
: Mutable, uses[]
tuple
: Immutable, uses()
tuple([1, 2, 3])
from array import array
array('i', [1, 2, 3])
Or using NumPy:
import numpy as np
np.array([1, 2, 3])
- Reference counting
- Garbage collection
- Memory pools
- Simple syntax
- Interpreted
- Dynamically typed
- Cross-platform
- Extensive libraries
- OOP and functional support
Reserved words (e.g., if
, class
, return
).
import keyword
print(keyword.kwlist)
- Numeric:
123
- String:
'abc'
- Boolean:
True
,False
- None:
None
- Collections:
[1]
,(1,)
,{1}
,{'a':1}
(1, 2) + (3, 4) # (1, 2, 3, 4)
- Class: Blueprint
- Instance: Object created from a class
x = 10
result = 'Even' if x % 2 == 0 else 'Odd'
import copy
shallow = copy.copy(obj)
deep = copy.deepcopy(obj)
- Via
threading
module - Limited by GIL (only one thread runs bytecode)
- Best for I/O-bound tasks
Functions that modify other functions:
@decorator
def func(): pass
*args
: Variable positional arguments**kwargs
: Variable keyword arguments
help(obj)
: Shows documentationdir(obj)
: Lists attributes/methods
- Python uses call by object reference
- Mutable objects can be changed; immutable can't
Modifying classes/modules at runtime.
import math
math.sqrt = lambda x: "patched!"
is
: Same memory==
: Same value
Groups data and applies aggregate functions:
df.groupby('col')['val'].sum()
.loc
: Label-based.iloc
: Index-based
- Compiled to bytecode (
.pyc
), then interpreted by PVM - No machine code compilation
- Easier debugging and portability
Python OOPs (Object-Oriented Programming) interview questions:
✅ Basic OOPs Concepts What is OOPs in Python?
What are the four pillars of OOPs?
Encapsulation, Abstraction, Inheritance, Polymorphism
What is a class and an object in Python?
How is init method used?
What is self in Python classes?
🔁 Inheritance & Polymorphism What is inheritance in Python?
Types of inheritance in Python?
What is method overriding?
What is method overloading?
What is multiple inheritance?
🔒 Encapsulation & Abstraction What is encapsulation in Python?
How do you implement abstraction?
What are private, protected, and public attributes?
🔧 Advanced OOP Concepts What is a class method and how is it defined?
What is a static method?
What are @classmethod and @staticmethod?
What is the difference between isinstance() and issubclass()?
What is composition vs inheritance?
What are dunder/magic methods (e.g., str, len)?
What is the purpose of super()?
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure software. Python supports OOP, allowing for modular, reusable, and scalable code.
- Encapsulation: Binding data and methods together and restricting access.
- Abstraction: Hiding complex implementation details and exposing only the necessary parts.
- Inheritance: Deriving new classes from existing ones.
- Polymorphism: Performing a single action in different ways.
- Class: A blueprint for creating objects. It defines attributes and methods.
- Object: An instance of a class with actual values.
class Car:
def __init__(self, brand):
self.brand = brand
my_car = Car("Toyota")
The __init__
method is a constructor called when an object is instantiated. It initializes the object’s attributes.
class Person:
def __init__(self, name):
self.name = name
self
represents the instance of the class. It is used to access attributes and methods within the class.
Inheritance allows a class (child) to inherit attributes and methods from another class (parent).
class Animal:
def speak(self):
return "Sound"
class Dog(Animal):
def speak(self):
return "Bark"
- Single
- Multiple
- Multilevel
- Hierarchical
- Hybrid
Defining a method in the child class with the same name as in the parent class to change its behavior.
Python does not support method overloading by default. It can be emulated using default parameters or *args
and **kwargs
.
A child class inheriting from more than one parent class.
class A:
pass
class B:
pass
class C(A, B):
pass
Encapsulation is restricting access to methods and variables using access modifiers (public, protected _
, private __
).
Using abstract base classes from the abc
module.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
- Public: Accessible from anywhere.
- Protected: Prefix with
_
, internal use. - Private: Prefix with
__
, inaccessible directly from outside.
Class methods use @classmethod
and take cls
as the first parameter.
class MyClass:
count = 0
@classmethod
def increment(cls):
cls.count += 1
Static methods use @staticmethod
and do not take self
or cls
as arguments.
class Math:
@staticmethod
def add(x, y):
return x + y
- @classmethod: Operates on the class.
- @staticmethod: Utility function with no access to class or instance.
isinstance(obj, Class)
checks ifobj
is an instance ofClass
.issubclass(Sub, Super)
checks ifSub
is a subclass ofSuper
.
- Inheritance: "is-a" relationship.
- Composition: "has-a" relationship; one class contains another.
Special methods with double underscores like __str__
, __len__
, __add__
used to define behavior of objects.
super()
is used to call the parent class methods.
class Parent:
def show(self):
print("Parent")
class Child(Parent):
def show(self):
super().show()
print("Child")