LearningTech

🚀

Python Advanced

In-depth concepts and advanced techniques

26. How do you delete a file using Python? â–¼

Using the os module:


import os

os.remove("data.txt")


To delete directories:


os.rmdir("folder")

27. Which sorting algorithm is used by sort() and sorted() functions in Python? â–¼

Python uses Timsort, a hybrid of merge sort and insertion sort.


Advantages:

  • Stable
  • Adaptive
  • Performs extremely well on partially sorted data
28. Differentiate between a list and a tuple in Python. â–¼

Feature List Tuple

Mutability Mutable Immutable

Syntax [1, 2, 3] (1, 2, 3)

Performance Slower Faster (no changes allowed)

Use Case Dynamic data Fixed data

29. What is slicing in Python? â–¼

Slicing extracts a portion of a sequence (string, list, tuple).


Syntax:


sequence[start:end:step]


Example:


nums = [0, 1, 2, 3, 4]

print(nums[1:4]) # [1, 2, 3]

print(nums[::-1]) # reverse list

30. How is multithreading achieved in Python? â–¼

Python uses the threading module.


Example:


import threading

def task(): print("Running")

t = threading.Thread(target=task)

t.start()


But due to the GIL (Global Interpreter Lock):

  • Threads cannot run Python bytecode in parallel
  • Best for I/O-bound tasks
  • CPU-heavy tasks should use multiprocessing.
31. Which is faster — Python lists or NumPy arrays? Why? ▼

NumPy arrays are faster.


Reasons:

  • Stored in contiguous memory
  • Implemented in C
  • Support vectorized operations
  • Avoid Python-level loops

Example:


import numpy as np

a = np.array([1,2,3])

print(a*2) # vectorized

32. Explain inheritance in Python. â–¼

Inheritance allows a class to derive attributes and methods from another.


class Parent: def greet(self): print("Hello")

class Child(Parent): pass

obj = Child()

obj.greet()


Types:

  • Single
  • Multiple
  • Multilevel
  • Hierarchical
  • Hybrid
33. How are classes created in Python? â–¼

Using the class keyword:


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

def show(self): print(self.model)

Objects are created like:


c = Car("Tesla")

34. Write a Python program to generate the Fibonacci series. â–¼

n = int(input("Enter limit: "))

a, b = 0, 1


for _ in range(n):

print(a, end=" ") a, b = b, a + b
35. What is the difference between shallow copy and deep copy in Python? â–¼

Shallow Copy


Copies outer structure, not nested objects.


import copy

a = [[1,2], [3,4]]

b = copy.copy(a)


Changes inside nested lists affect both.


Deep Copy


Copies everything recursively.


c = copy.deepcopy(a)


Changes don’t reflect in the original.

36. What is the process of compilation and linking in Python? â–¼

Python does not use traditional compilation and linking.


Steps:

1. Source code (.py) 2. Compiled into bytecode (.pyc) 3. Bytecode executed by the PVM 4. No linking step like C/C++
37. Explain the use of break, continue, and pass statements in Python. â–¼

break


Exits loop immediately.


for i in range(10):

if i == 5: break

continue


Skips current iteration.


for i in range(5):

if i == 2: continue

pass


Does nothing; placeholder.


def func(): pass
38. What is PEP8? â–¼

PEP8 is Python’s official style guide.

It defines how Python code should look:

  • Naming conventions
  • Indentation rules
  • Spacing
  • Line length
  • Imports

It ensures readable, consistent code.

39. What is an expression in Python? â–¼

An expression is any valid combination of:

  • Variables
  • Operators
  • Values
  • Function calls

Example:


x = (a + b) * c


It evaluates to a single value.

40. What is the purpose of the double equals (==) operator in Python? â–¼

== checks value equality.


3 == 3 # True

[1,2] == [1,2] # True


(Not to be confused with is, which checks identity.)

41. What is type conversion in Python? â–¼

Converting a value from one type to another:

  • int()
  • float()
  • str()
  • list()
  • tuple()

Example:


x = int("5")

42. Name some commonly used built-in modules in Python. â–¼

Popular ones include:

  • os
  • sys
  • math
  • random
  • datetime
  • json
  • re
  • logging
  • subprocess
  • statistics
43. If you want, I can convert all these Q&A into a polished HTML, PDF, or one-page interview cheatsheet. â–¼

Here comes a sharp, interview-ready set of answers, explained cleanly and with a light creative shimmer, without losing precision.

44. Difference between xrange() and range() â–¼

xrange() existed only in Python 2, while range() in Python 3 behaves like Python 2’s xrange().


Python 2

  • range() returns a list.
  • xrange() returns an efficient sequence object (lazy evaluation).

Python 3

  • Only range() exists, and it is lazy, memory-efficient, and equivalent to Python 2’s xrange().

Example (Python 3):


r = range(1, 5)

list(r) # [1, 2, 3, 4]

45. What is the zip() function in Python? â–¼

zip() pairs elements of multiple iterables together.


Example:


names = ["Aarav", "Pahal"]

ages = [13, 5]


result = list(zip(names, ages))

print(result) # [('Aarav', 13), ('Pahal', 5)]


If iterables differ in size, zip() stops at the shortest.

46. What is Django architecture? â–¼

Django follows the MTV architecture, a variant of MVC.


M – Model


Handles database schema, ORM, and business logic.


T – Template


Handles UI rendering (HTML, text, JSON).


V – View


Contains the request–response logic.


The flow is:

User request → URL dispatcher → View → Model → Template → Response

47. What is inheritance in Python? Explain its types. â–¼

Inheritance allows a class to acquire properties of another class.


Example:


class Parent: pass

class Child(Parent): pass

Types of Inheritance

1. Single

class A: pass class B(A): pass


2. Multiple

class C(A, B): pass


3. Multilevel

class A: pass class B(A): pass class C(B): pass


4. Hierarchical

class Parent: pass class Child1(Parent): pass class Child2(Parent): pass


5. Hybrid

Combination of the above.

48. Define *args and **kwargs in Python. â–¼

They let functions accept a flexible number of parameters.


*args


Collects extra positional arguments as a tuple.


def demo(*args): print(args)

**kwargs


Collects extra keyword arguments as a dictionary.


def demo(**kwargs): print(kwargs)
49. Do runtime errors exist in Python? Give examples. â–¼

Yes. Examples include:


print(10 / 0) # ZeroDivisionError

int("abc") # ValueError

a = [1, 2]; a[5] # IndexError

{}["key"] # KeyError


Python detects them at runtime.

50. What are docstrings in Python? â–¼

A docstring is a string literal placed as the first statement inside a module, class, or function to document it.


Example:


def add(a, b): """Returns the sum of two numbers.""" return a + b

Retrieve using:


print(add.__doc__)