Skip to content
Home » Blog » Python Terminology Cheat Sheet for Interviews – An Ultimate Guide

Python Terminology Cheat Sheet for Interviews – An Ultimate Guide

Introduction

Preparing for a Python interview can feel stressful, especially when you run into tricky technical terms. But don’t worry—I’ve got you! Here is the Python Terminology Cheat Sheet.

This Python terminology cheat sheet covers the most important terms you’ll need. You’ll go through data types, loops, functions, OOP, exception handling, and more. Whether you’re just starting or brushing up, this guide will make things simple.

Knowing these terms will help you explain your answers better and feel more confident. Let’s get started!

Core Python Concepts

A colorful grid-style infographic displaying a Python Terminology Cheat Sheet, with sections covering Core Python Concepts, OOP, Advanced Topics, Memory Management, Modules & Packages, Data Structures, File Handling, and Multithreading & Multiprocessing. Each section has a unique background color and lists key subtopics in an easy-to-read format.
Python Terminology Cheat Sheet

Variables & Data Types

Think of variables as boxes where you store data. In Python, you don’t have to say what type of data you’re storing—Python figures it out for you.

Example:

x = 10        # A whole number (integer)  
name = "Alex" # A piece of text (string)  
pi = 3.14     # A decimal number (float)  

So if you write x = 10, Python just knows it’s a number. No need to say int x = 10; like in other languages.

Common Data Types

Python has different types of data, and each one is used for a specific purpose.

  • Integers (int) → Whole numbers
age = 25  
  • Floats (float) → Numbers with decimals
price = 9.99  
  • Strings (str) → Text inside quotes
name = "Python"  
  • Lists (list) → A collection of items that can change
fruits = ["apple", "banana", "cherry"]  
  • Tuples (tuple) → Like lists, but can’t be changed
colors = ("red", "blue", "green")  
  • Sets (set) → A collection of unique items, no duplicates
unique_numbers = {1, 2, 3, 3}  # Python automatically removes duplicate 3  
  • Dictionaries (dict) → Key-value pairs, like a mini database
person = {"name": "Alice", "age": 30}  

Mutable vs Immutable

Some data types in Python can be changed after they’re created, and some can’t.

  • Mutable (can be changed)list, set, dict
fruits = ["apple", "banana"]  
fruits.append("cherry")  # This works!  
  • Immutable (can’t be changed)str, tuple, int, float
name = "Python"  
name[0] = "J"  # ❌ This gives an error! Strings can’t be changed like this  

Interview Tips

  • If you need a list that never changes, use a tuple instead of a list.
  • When you only need unique values, use a set—Python removes duplicates for you.
  • If you want to store key-value pairs (like a name and an age), use a dictionary.
  • Strings are immutable, so every time you change one, Python creates a new string.

Operators

Operators are special symbols that let you perform operations on variables and values. Python has different types of operators, each with its own job.

Arithmetic Operators (Math Stuff)

These are used for basic math operations.

  • + (Addition) → Adds two numbers.
x = 5 + 3  # x is 8
  • - (Subtraction) → Subtracts one number from another.
y = 10 - 4  # y is 6
  • * (Multiplication) → Multiplies two numbers.
* (Multiplication) → Multiplies two numbers
  • / (Division) → Divides one number by another (gives a decimal).
a = 10 / 2  # a is 5.0
  • % (Modulus) → Gives the remainder of a division.
b = 10 % 3  # b is 1 (since 10 ÷ 3 = 3 remainder 1)
  • ** (Exponent) → Raises a number to a power.
c = 2 ** 3  # c is 8 (2³)

Quick Tip:
Use % (modulus) to check if a number is even or odd:

num = 7  
if num % 2 == 0:  
    print("Even")  
else:  
    print("Odd")  

Comparison Operators (Checking Things)

These compare two values and return True or False.

  • == (Equal to) → Checks if two values are the same.
5 == 5  # True
  • != (Not equal to) → Checks if two values are different.
5 != 3  # True
  • > (Greater than) → Checks if the first value is bigger.
10 > 5  # True
  • < (Less than) → Checks if the first value is smaller.
3 < 7  # True
  • >= (Greater than or equal to) → Checks if the first value is bigger or equal.
5 >= 5  # True
  • <= (Less than or equal to) → Checks if the first value is smaller or equal.
4 <= 6  # True

Quick Tip:
Use == for comparison, not = (which is for assignment).

x = 10  # Assigns 10 to x
if x == 10:  # Compares x with 10
    print("x is 10")

A structured mind map illustrating core Python concepts, including Variables & Data Types, Operators, Control Flow, and Functions. Each category branches into subtopics with rectangular labels and connecting lines.
Mind Map of Core Python Concepts – A structured visualization of Python fundamentals, covering variables, operators, control flow, and functions.

Logical Operators (Combining Conditions)

These are used when you need to check multiple conditions at once.

  • and → Returns True if both conditions are true.
(5 > 2) and (10 > 3)  # True
  • or → Returns True if at least one condition is true.
(5 > 2) or (10 < 3)  # True
  • not → Reverses the result (True becomes False, and vice versa).
not (5 > 2)  # False

Quick Tip:
Use and when both conditions must be true, and or when at least one must be true.

age = 20
if age > 18 and age < 30:
    print("You're in your 20s!")  

Bitwise Operators (For Binary Stuff)

These work on numbers at the binary (bit) level. You won’t use them much unless you’re working with low-level programming or optimization.

  • & (AND) → Compares bits and keeps only the 1s that match.
5 & 3  # 5 (101) & 3 (011) = 1 (001)
  • | (OR) → Compares bits and keeps any 1s it finds.
5 | 3  # 5 (101) | 3 (011) = 7 (111)
  • ^ (XOR) → Keeps 1s where the bits are different.
5 ^ 3  # 5 (101) ^ 3 (011) = 6 (110)
  • << (Left Shift) → Moves bits to the left (multiplies by 2).
5 << 1  # 5 (101) becomes 10 (1010)
  • >> (Right Shift) → Moves bits to the right (divides by 2).
5 >> 1  # 5 (101) becomes 2 (10)

Quick Tip:
Use left shift << to multiply by powers of 2, and right shift >> to divide by powers of 2.

x = 4  
print(x << 1)  # 8 (4 * 2)  
print(x >> 1)  # 2 (4 / 2)  

Control Flow

Control flow is how Python decides what to run next in your code. It’s like giving your program a set of rules to follow.

If-Else (Making Decisions)

The if statement helps your code make choices. It runs a block of code only if a certain condition is true.

age = 18  

if age >= 18:  
    print("You're an adult!")  
else:  
    print("You're a minor!")  

Quick Tip:
Use elif (short for “else if”) when checking multiple conditions.

score = 85  

if score >= 90:  
    print("Grade: A")  
elif score >= 80:  
    print("Grade: B")  
else:  
    print("Grade: C")  

Loops (Repeating Things)

Loops let you run the same code multiple times without repeating yourself.

For Loop (Go Through a Sequence)

A for loop runs through a list, string, or range of numbers one item at a time.

fruits = ["apple", "banana", "cherry"]  

for fruit in fruits:  
    print(fruit)  

Quick Tip:
Use range(n) to loop through numbers from 0 to n-1.

for i in range(5):  
    print(i)  # Prints 0, 1, 2, 3, 4  
While Loop (Repeat Until False)

A while loop keeps running as long as a condition is true.

count = 1  

while count <= 5:  
    print(count)  
    count += 1  # Increase count to avoid an infinite loop  

Be Careful!
If the condition never becomes false, the loop won’t stop (infinite loop!).

while True:  
    print("This will run forever!")  # Don’t do this!  

Loop Control Statements (Changing Loop Behavior)

These help you control how a loop behaves.

Break (Exit the Loop Immediately)

Use break to stop the loop early when a condition is met.

for num in range(10):  
    if num == 5:  
        break  # Stops the loop when num is 5  
    print(num)  
Continue (Skip the Current Iteration)

Use continue to skip the current loop iteration and move to the next one.

for num in range(5):  
    if num == 2:  
        continue  # Skips 2  
    print(num)  
Pass (Do Nothing, Just a Placeholder)

pass is used when you need a placeholder but don’t want your code to break.

for num in range(5):  
    if num == 2:  
        pass  # Does nothing  
    print(num)  

Quick Tip:
Use pass when writing code that you’ll fill in later.

Functions (Reusable Code Blocks)

Functions let you group code into a single block so you can reuse it without repeating yourself. This makes your code cleaner and easier to manage.

Defining a Function

You create a function using the def keyword.

def greet():  
    print("Hello, welcome!")  

To use the function, just call it by its name:

greet()  # Output: Hello, welcome!  

Quick Tip: Always give your functions clear names so others can understand what they do.

Functions with Parameters (Passing Values)

You can pass values (parameters) to a function.

def greet(name):  
    print(f"Hello, {name}!")  

greet("Alice")  # Output: Hello, Alice!  

Quick Tip: Functions can have multiple parameters too.

def add(a, b):  
    return a + b  

print(add(5, 3))  # Output: 8  

Default Parameters (Optional Values)

You can set default values for parameters.

def greet(name="Guest"):  
    print(f"Hello, {name}!")  

greet()  # Output: Hello, Guest!  
greet("Bob")  # Output: Hello, Bob!  

Quick Tip: Default parameters are useful when you don’t always need to provide a value.

Lambda Functions (Short, One-Line Functions)

Lambda functions are tiny functions that don’t need a def keyword.

square = lambda x: x * x  
print(square(4))  # Output: 16  

When to Use Lambda?

  • When you only need a quick function
  • Inside map(), filter(), or sorted()

Example:

numbers = [1, 2, 3, 4]  
squared = list(map(lambda x: x**2, numbers))  
print(squared)  # Output: [1, 4, 9, 16]  

Object-Oriented Programming (OOP) in Python

A structured mind map illustrating Object-Oriented Programming (OOP) in Python, including Classes & Objects, Encapsulation, Inheritance, and Dunder Methods, with rectangular labels and connecting lines.
Mind Map of Object-Oriented Programming in Python – A structured visualization of OOP fundamentals, covering classes, inheritance, encapsulation, and dunder methods.

Classes & Objects (Building Blocks of OOP in Python)

Python is an object-oriented programming (OOP) language. This means you can create blueprints (classes) and make real-world objects from them.

What’s a Class?

A class is like a template for creating objects. It defines what an object should have (attributes) and what it can do (methods).

class Car:  
    def __init__(self, brand):  
        self.brand = brand  # Attribute (stores car brand)  

Think of a class like a blueprint for a house. The blueprint tells you what a house should have (rooms, doors, windows), but it’s not a house itself.

What’s an Object?

An object is an actual thing created from a class.

my_car = Car("Toyota")  
print(my_car.brand)  # Output: Toyota  

If the class is a blueprint, an object is the house you build from it!

The __init__ Method (Constructor)

__init__ is a special method that runs automatically when you create an object. It’s used to set up attributes.

class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  

p1 = Person("Alice", 25)  
print(p1.name)  # Output: Alice  
print(p1.age)   # Output: 25  

self refers to the current object and lets you store values inside it.

Adding Methods (What an Object Can Do)

A class can have methods (functions inside a class) that perform actions.

class Dog:  
    def __init__(self, name):  
        self.name = name  

    def bark(self):  
        print(f"{self.name} says Woof!")  

d1 = Dog("Buddy")  
d1.bark()  # Output: Buddy says Woof!  

Methods let objects do things! Here, every Dog object can bark().

Multiple Objects (Each One Is Unique)

You can create many objects from the same class.

car1 = Car("Honda")  
car2 = Car("Ford")  

print(car1.brand)  # Output: Honda  
print(car2.brand)  # Output: Ford  

Each object has its own data! Changing car1.brand won’t affect car2.brand.

Why Use Classes & Objects?

  • Reusability – Create many objects from one class
  • Organization – Group data and behavior together
  • Scalability – Easily expand your code

Encapsulation (Hiding Data for Security & Control)

Encapsulation means restricting access to certain data in a class. This prevents accidental modification.

  • Public variables: Can be accessed anywhere (self.name).
  • Private variables: Have double underscores (__salary). These can’t be accessed directly from outside the class.
class Employee:  
    def __init__(self, name, salary):  
        self.name = name  # Public variable  
        self.__salary = salary  # Private variable  

    def get_salary(self):  # Public method to access private data  
        return self.__salary  

emp = Employee("John", 50000)  
print(emp.name)  # Output: John  
# print(emp.__salary)  # ❌ This will give an error  
print(emp.get_salary())  # ✅ Correct way to access private data (Output: 50000)  

Why use encapsulation? It protects sensitive data and only allows access through controlled methods.

Inheritance (Reusing Code by Extending Classes)

Inheritance allows a class (child class) to reuse the code of another class (parent class).

  • The child class gets all the methods and attributes of the parent.
  • It can also override them to change behavior.
class Animal:  
    def speak(self):  
        print("This animal makes a sound")  

class Dog(Animal):  # Dog inherits from Animal  
    def speak(self):  
        print("Woof! Woof!")  

dog = Dog()  
dog.speak()  # Output: Woof! Woof!  

Why use inheritance? It reduces code repetition and makes programs more organized.

Polymorphism (Same Method, Different Behavior)

Polymorphism means using the same method name in different ways.

Example: Different classes have a speak() method, but they behave differently.

class Cat:  
    def speak(self):  
        print("Meow!")  

class Bird:  
    def speak(self):  
        print("Chirp!")  

# Using the same method name across different classes  
animals = [Cat(), Bird()]  
for animal in animals:  
    animal.speak()  

# Output:  
# Meow!  
# Chirp!  

Why use polymorphism? It allows flexibility—you can write general code that works with different object types.

Dunder (Magic) Methods

Python has special methods called dunder (double underscore) methods. These start and end with __.

__init__ (Constructor Method – Runs When Object is Created)

This automatically initializes attributes when you create an object.

class Car:  
    def __init__(self, brand):  
        self.brand = brand  

my_car = Car("Tesla")  
print(my_car.brand)  # Output: Tesla  

Why use __init__? It saves you from manually setting attributes every time you create an object.

__str__ (How an Object is Printed as a String)

By default, printing an object gives something unreadable like <__main__.Car object at 0x0000023B>.

With __str__, you control how an object is displayed.

class Car:  
    def __init__(self, brand):  
        self.brand = brand  

    def __str__(self):  
        return f"Car Brand: {self.brand}"  

my_car = Car("BMW")  
print(my_car)  # Output: Car Brand: BMW  

Why use __str__? It makes debugging easier by showing useful info instead of memory addresses.

Encapsulation, Inheritance, and Polymorphism help structure code in a way that’s secure, reusable, and flexible. And dunder methods make objects more intuitive to work with.

For your interview: Be ready to explain these concepts and write simple examples!


Must Read


Advanced Python Concepts

A structured mind map illustrating Advanced Python Concepts, including List Comprehensions & Generators, Decorators & Closures, Iterators & Iterables, and Exception Handling, with rectangular labels and connecting lines.
Mind Map of Advanced Python Concepts – A structured visualization covering advanced Python topics like list comprehensions, decorators, iterators, and exception handling.

List Comprehensions (Shortcuts for Creating Lists)

List comprehensions let you create lists in a single line instead of using loops. They’re faster and cleaner.

Example: Create a list of squares from 0 to 4.

squares = [x * x for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]

Tip: You can also use conditions inside list comprehensions!

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # Output: [0, 2, 4, 6, 8]

Generators (Efficient Way to Handle Large Data)

Generators produce values one at a time instead of storing them all in memory. This is useful for large datasets.

Example: A generator that produces squares on demand.

def square_generator(n):
    for x in range(n):
        yield x * x  # 'yield' returns one value at a time

gen = square_generator(5)
print(next(gen))  # Output: 0
print(next(gen))  # Output: 1

Tip: Generators are memory-efficient because they don’t store all values at once. Use them when working with large files or infinite sequences.

Decorators & Closures

Decorators (Modify Functions Without Changing Their Code)

A decorator is a function that wraps another function to modify its behavior.

Example: A decorator that logs function calls.

def logger(func):
    def wrapper():
        print(f"Calling {func.__name__}()")
        func()
    return wrapper

@logger
def say_hello():
    print("Hello!")

say_hello()
# Output:
# Calling say_hello()
# Hello!

Tip: Use decorators to add logging, authentication, or timing to functions without modifying their original code.

Closures (Functions That Remember Variables)

A closure is a function that remembers variables from its enclosing scope even after the scope has finished executing.

Example:

def outer_function(msg):
    def inner_function():
        print(msg)  # 'msg' is remembered even after outer_function finishes
    return inner_function

greet = outer_function("Hi there!")
greet()  # Output: Hi there!

Tip: Closures are useful for data hiding and creating function factories.

Iterators & Iterables

Iterables (Objects You Can Loop Through)

An iterable is any object you can loop through (lists, tuples, dictionaries, etc.).

numbers = [1, 2, 3]
for num in numbers:
    print(num)  # Output: 1 2 3

Iterators (Remember Position While Looping)

An iterator is an object that remembers where it is in a sequence. It works with the next() function.

Example: Manually iterating through a list.

numbers = iter([1, 2, 3])
print(next(numbers))  # Output: 1
print(next(numbers))  # Output: 2

Tip: Use iter() and next() when you don’t want to load everything in memory at once.

Exception Handling (try-except-finally)

Exceptions happen when your code runs into an error (like dividing by zero). Instead of crashing the program, you can handle errors gracefully.

Example: Handling division by zero.

try:
    x = 1 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
finally:
    print("This runs no matter what.")

Tip: The finally block always runs, whether there’s an error or not. Use it to close files, release resources, or clean up memory.

Mastering list comprehensions, generators, decorators, iterators, and exception handling will make you write cleaner, more efficient Python code. These are common topics in coding interviews, so practice them well!

Memory Management & Performance

A structured mind map illustrating Memory Management & Performance in Python, including Garbage Collection & Reference Counting, Global Interpreter Lock (GIL), and Shallow vs Deep Copy, with rectangular labels and connecting lines.
Mind Map of Memory Management & Performance – A structured visualization covering Python’s garbage collection, GIL, and memory copying methods.

Garbage Collection & Reference Counting

Python automatically cleans up unused objects to free memory. This process is called garbage collection.

How It Works

  • Python keeps track of how many variables are pointing to an object. This is called reference counting.
  • When an object’s reference count drops to zero, Python deletes it to free up memory.

Example:

import sys

x = [1, 2, 3]
y = x  # Now, two variables point to the same list
print(sys.getrefcount(x))  # Output: 3 (x, y, and an internal reference)

del x  # Remove one reference
print(sys.getrefcount(y))  # Output: 2

Tip: Circular references (objects pointing to each other) can prevent garbage collection. Use gc.collect() to force cleanup when needed.

Global Interpreter Lock (GIL)

Python uses something called the Global Interpreter Lock (GIL). This means only one thread can execute Python code at a time, even on multi-core processors.

Why Does This Matter?

  • If your program uses multiple threads, they take turns running instead of running in parallel.
  • This is fine for I/O-bound tasks (like reading files or making network requests).
  • But for CPU-heavy tasks, using multiple processes (multiprocessing) is better than threads.

Example: Using threading vs. multiprocessing:

import threading
import multiprocessing

def task():
    print("Running...")

# Threading (affected by GIL)
t = threading.Thread(target=task)
t.start()

# Multiprocessing (bypasses GIL)
p = multiprocessing.Process(target=task)
p.start()

Tip: If you need true parallel processing, use the multiprocessing module instead of threading.

Shallow Copy vs. Deep Copy

Shallow Copy (Copies References, Not Data)

A shallow copy creates a new object, but it still points to the original data. Changes to nested objects will reflect in both copies.

Example:

import copy

original = [[1, 2, 3], [4, 5, 6]]
shallow_copy = copy.copy(original)

shallow_copy[0][0] = 99
print(original)  # Output: [[99, 2, 3], [4, 5, 6]]

Tip: Use shallow copies when you don’t need to fully separate objects.

Deep Copy (Creates a Completely New Object)

A deep copy makes a completely independent copy. Changes in the new object won’t affect the original.

Example:

deep_copy = copy.deepcopy(original)

deep_copy[0][0] = 42
print(original)  # Output: [[99, 2, 3], [4, 5, 6]] (Unchanged)

Tip: Use deepcopy() when working with nested structures and you want a true copy.

Final Thoughts

  • Garbage collection helps manage memory, but circular references can cause issues.
  • The GIL limits multi-threading in Python, so use multiprocessing for CPU-heavy tasks.
  • Shallow copies share data, while deep copies create completely independent objects.

These are common interview topics, so practice them well!

Python Modules & Packages

Importing Modules

A module is just a Python file that contains functions, classes, or variables you can reuse in other programs. Instead of writing everything from scratch, you can import code from other files or external libraries.

How to Import a Module

You can import a module using the import statement:

import math  # Imports the entire math module

print(math.sqrt(25))  # Output: 5.0

Tip: Use import module_name as alias to make names shorter:

import numpy as np

arr = np.array([1, 2, 3])
print(arr)  # Output: [1 2 3]

Importing Specific Parts of a Module

Instead of importing the whole module, you can import only what you need:

from math import sqrt, pi

print(sqrt(36))  # Output: 6.0
print(pi)  # Output: 3.141592653589793

Tip: This makes your code cleaner and faster since it doesn’t load unnecessary functions.

Creating Your Own Module

You can create your own custom module by saving a Python file (.py) and importing it:

Example: Create my_module.py

def greet(name):
    return f"Hello, {name}!"

Now, import and use it in another script:

import my_module

print(my_module.greet("Alice"))  # Output: Hello, Alice!

Virtual Environments & Package Management

Why Use Virtual Environments?

A virtual environment (venv) is a separate space where you can install packages without affecting your system Python. This is useful for keeping projects isolated.

Creating and Activating a Virtual Environment

Steps to create a virtual environment:

python -m venv myenv  # Creates a virtual environment named 'myenv'

Activate the virtual environment:

  • Windows:
myenv\Scripts\activate
  • Mac/Linux:
source myenv/bin/activate

Once activated, your terminal will show (myenv), meaning you’re inside the virtual environment.

Tip: Use deactivate to exit the virtual environment.

Installing Packages with pip

pip is Python’s package manager. It lets you install and manage external libraries.

Install a package:

pip install numpy

Install multiple packages from a requirements file:

pip install -r requirements.txt

Save installed packages to a file:

pip freeze > requirements.txt

Tip: Always use a virtual environment when working on projects to avoid package conflicts.

Final Thoughts

  • Modules let you reuse code and keep your projects organized.
  • Use specific imports (from module import function) to keep code clean.
  • Virtual environments help keep dependencies isolated for different projects.
  • Use pip to install and manage Python packages easily.

These are important skills for any Python interview.

Data Structures in Python

Lists, Tuples, Sets, and Dictionaries

These are the most commonly used data structures in Python. Each one has its own purpose, so let’s break them down in simple terms.

1. Lists (Ordered, Mutable)

A list is like a shopping list—it keeps items in the same order, and you can add, remove, or change items anytime.

my_list = [1, 2, 3, 4]  # A simple list
my_list.append(5)  # Adds 5 to the end
print(my_list)  # Output: [1, 2, 3, 4, 5]

Tip: Use .append() to add an item and .pop() to remove the last one.

my_list.pop()  # Removes 5

2. Tuples (Ordered, Immutable)

A tuple is like your date of birth—it never changes. Once created, you cannot modify it.

my_tuple = (1, 2, 3)  # A tuple

If you try to change it:

my_tuple[0] = 10  # ❌ This will cause an error!

Tip: Tuples are faster than lists, so use them when data won’t change.

3. Sets (Unordered, Unique Values)

A set is like a basket of apples—you can’t have duplicates, and the order doesn’t matter.

my_set = {1, 2, 3, 3}  # Duplicate 3 is ignored
print(my_set)  # Output: {1, 2, 3}

Tip: Use sets for removing duplicates from a list.

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)  
print(unique_numbers)  # Output: {1, 2, 3, 4, 5}

4. Dictionaries (Key-Value Pairs)

A dictionary is like a phonebook—you store keys (names) and values (phone numbers).

my_dict = {'name': 'Alice', 'age': 25}
print(my_dict['name'])  # Output: Alice

Tip: Use .keys() to get all keys and .values() to get all values.

print(my_dict.keys())  # Output: dict_keys(['name', 'age'])
print(my_dict.values())  # Output: dict_values(['Alice', 25])

Stacks & Queues (Using collections Module)

Sometimes, you need to store data in a specific order. That’s where stacks and queues come in.

1. Stack (LIFO – Last In, First Out)

A stack is like a stack of plates—you always remove the top one first (Last In, First Out).

stack = []  
stack.append(1)  # Push 1
stack.append(2)  # Push 2
stack.pop()  # Removes 2 (LIFO)

Tip: Use .append() to push and .pop() to remove the last item.

2. Queue (FIFO – First In, First Out)

A queue is like a line at a ticket counter—the first person to enter is the first to leave.

Use collections.deque (better performance than lists).

from collections import deque  

queue = deque()  
queue.append(1)  # Add to queue
queue.append(2)  
queue.popleft()  # Removes 1 (FIFO)

Tip: .append() adds to the queue, and .popleft() removes the first item.

Final Notes

  • Lists – when you need an ordered, changeable collection.
  • Tuples – when data shouldn’t change.
  • Sets – when you need unique values.
  • Dictionaries – to store key-value pairs.
  • Stacks – when last in should go out first.
  • Queues – when first in should go out first.

These concepts often come up in coding interviews, so make sure to practice them!

File Handling & I/O Operations

Reading & Writing Files in Python

Working with files is a must-have skill, whether you’re dealing with text, CSV, or JSON. Here’s a quick and practical breakdown of how to do it.

1. Reading a File (📖 Open & Read)

If you want to read a file’s content, use the "r" mode (read mode).

with open("file.txt", "r") as f:
    content = f.read()  
print(content)  # Displays the file's content

Tip: Using with open(...) automatically closes the file, so you don’t need to worry about closing it manually.

2. Writing to a File (✍️ Create or Overwrite)

If you need to write to a file, use the "w" mode (write mode).

with open("file.txt", "w") as f:
    f.write("Hello, Python!")  

Warning: "w" overwrites the file’s content. If you want to add new content instead of replacing, use "a" (append mode).

with open("file.txt", "a") as f:
    f.write("\nAppending new line!")

3. Reading Files Line by Line

If you’re working with large files, reading line by line is more efficient.

with open("file.txt", "r") as f:
    for line in f:
        print(line.strip())  # Removes extra spaces & newlines

Tip: .strip() removes unwanted spaces and \n characters at the end of each line.

Handling CSV & JSON Files

4. Reading & Writing CSV Files (Data Tables)

CSV (Comma-Separated Values) files are common in data processing. Python’s csv module makes them easy to handle.

Reading a CSV file:

import csv  

with open("data.csv", "r") as f:
    reader = csv.reader(f)  
    for row in reader:
        print(row)  # Each row is a list

Writing to a CSV file:

with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)  
    writer.writerow(["Name", "Age"])  
    writer.writerow(["Alice", 25])  

Tip: newline="" prevents extra blank lines in Windows when writing CSV files.

5. Handling JSON Files (Storing Data as Key-Value Pairs)

JSON (JavaScript Object Notation) is great for storing and transferring structured data. Python’s json module makes it easy.

Writing Python data to a JSON file:

import json  

data = {"name": "Alice", "age": 25}  

with open("data.json", "w") as f:
    json.dump(data, f)  # Save JSON file

Reading a JSON file into Python:

with open("data.json", "r") as f:
    data = json.load(f)  # Load JSON file
print(data)  # Output: {'name': 'Alice', 'age': 25}

Tip: If you need to convert Python objects to/from JSON strings (instead of files), use:

json_str = json.dumps(data)  # Convert to JSON string
python_data = json.loads(json_str)  # Convert back to Python dictionary

Final Notes

  • Use "r" for reading, “w” for writing, and “a” for appending.
  • Use CSV for tabular data and JSON for structured data.
  • Always use with open(...) to avoid file handling issues.

Mastering file handling is crucial for working with real-world data.

Multithreading & Multiprocessing

Threads vs. Processes in Python

Python lets you run multiple tasks simultaneously using threads and processes, but they work differently.

1. Threads vs. Processes: What’s the Difference?

FeatureThreads Processes
DefinitionA thread is a lightweight unit inside a process.A process is an independent program in execution.
MemoryThreads share memory (faster but riskier).Each process has its own memory (safer but uses more resources).
SpeedFaster since threads share the same space.Slower due to separate memory and communication overhead.
Crash ImpactA crashing thread doesn’t affect others in the process.If a process crashes, it dies completely.

Example:
If you open Google Chrome, it starts as a process. Each tab runs as a separate process. Inside each tab, multiple threads handle tasks like rendering pages and downloading files.

2. Creating Threads & Processes in Python

Using threading Module

import threading  

def print_numbers():
    for i in range(5):
        print(i)

t1 = threading.Thread(target=print_numbers)  
t1.start()  # Start the thread  
t1.join()   # Wait for the thread to finish  

Creating a Process (Using multiprocessing Module)

import multiprocessing  

def print_numbers():
    for i in range(5):
        print(i)

p1 = multiprocessing.Process(target=print_numbers)  
p1.start()  # Start the process  
p1.join()   # Wait for the process to finish  

Key Difference:

  • Thread shares the same memory as the main program.
  • Process runs separately and doesn’t share memory.

3. Thread Synchronization & Locks (Avoiding Race Conditions)

When multiple threads try to modify the same data at the same time, things can go wrong! 😨 This is called a race condition.

Solution: Use Locks to prevent multiple threads from accessing the same resource at the same time.

Example Without Lock (Risky )

import threading  

counter = 0  

def increase():
    global counter
    for _ in range(1000000):
        counter += 1  

t1 = threading.Thread(target=increase)  
t2 = threading.Thread(target=increase)  

t1.start()
t2.start()

t1.join()
t2.join()

print("Final Counter:", counter)  # The output is unpredictable 😬  

Example With Lock (Safe )

import threading  

counter = 0  
lock = threading.Lock()  

def increase():
    global counter
    for _ in range(1000000):
        with lock:  # Ensures only one thread changes 'counter' at a time
            counter += 1  

t1 = threading.Thread(target=increase)  
t2 = threading.Thread(target=increase)  

t1.start()
t2.start()

t1.join()
t2.join()

print("Final Counter:", counter)  # Always correct ✅  

Final Takeaways

  • Threads when you need to do multiple tasks in the same program (like handling multiple requests in a web server).
  • Processes when tasks shouldn’t share memory (like running independent scripts).
  • locks when working with shared data in threads to avoid unexpected results.

Conclusion: Ace Your Python Interview with Confidence!

Mastering Python terminology is a game-changer for technical interviews. Understanding key concepts like OOP, data structures, exception handling, and memory management helps you write clean, efficient code while impressing interviewers.

But memorization isn’t enough—practice is key! Work on real coding problems, explore Python’s built-in modules, and always think out loud when explaining solutions.

Keep sharpening your skills, stay curious, and approach every interview with confidence. Your next Python job is just one well-prepared answer away!

FAQs on Python Terminology for Interviews

1. Do I need to memorize all Python terms for an interview?

No, but you should understand the key concepts and how they work. Instead of memorizing definitions, focus on applying them in code and explaining them clearly.

2. What’s the difference between a list and a tuple?

List: Mutable (can change), uses [], slower but flexible.
Tuple: Immutable (can’t change), uses (), faster and good for fixed data.

3. How is Python different from other programming languages?

Python is easy to read, dynamically typed, and has built-in memory management. It’s widely used for web development, data science, AI, and automation.

4. What is the Global Interpreter Lock (GIL), and why does it matter?

GIL allows only one thread to run at a time in Python, even on multi-core processors. This can limit multi-threading performance but can be bypassed using multiprocessing.

5. What’s the best way to prepare for a Python coding interview?

Practice coding problems on LeetCode, CodeSignal, or HackerRank.
Review common Python concepts like OOP, exception handling, and list comprehensions.
Work on real-world projects to understand Python beyond theory.
Explain your thought process clearly during coding challenges.

External Resources

Python Documentation

Official Python Docs – The ultimate reference for Python syntax, libraries, and best practices.

2. Coding Practice Platforms

HackerRank – Python Challenges – Great for beginners to advanced coders.
CodeSignal – Simulated interview assessments to test your skills.

3. Python Job Boards & Career Growth

LinkedIn Jobs – Find Python-related job openings.
Turing – Remote Python developer jobs.

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Rating