Knowledge / Computer Science and Engineering / Python essentials

Python essentials

Computer Science and Engineering (B.E./B.Tech) · Programming · free study notes for exams, placements and interviews

In short

Python is a high-level, dynamically typed, interpreted language in which everything is an object and names are only references to objects. Its small syntax, huge standard library and the NumPy/Pandas/Django/Flask ecosystem make it the default language for data, automation, testing, scripting and backend work in Indian IT services and product companies. It appears in first-year AICTE/CBCS "Programming for Problem Solving" and "Python Programming" papers, in the GATE Data Science and AI (DA) paper, and in almost every campus coding round (TCS NQT, Infosys, Wipro, Cognizant, Zoho, Accenture) where candidates may answer in Python. Interviewers test the object model - mutability, references, copying, scoping - far more than syntax.

Explained

Language model, execution and typing

Built-in data types and mutability

Operators, strings and control flow

Functions, scope and iteration machinery

Memory management, performance and concurrency

Operationlistdict / setstr
index / key lookupO(1)O(1) average, O(n) worstO(1)
append / addO(1) amortisedO(1) averageimmutable
insert / delete at frontO(n)--
membership inO(n)O(1) averageO(n·m) substring
sortO(n log n) (Timsort)--

Modules, packages, files and the ecosystem

Key points

Formulas and examples

len(range(start, stop, step)) = max(0, ⌈(stop − start)/step⌉) for step > 0 — number of values produced; same formula gives the length of slice s[start:stop:step]
a = b·q + r where q = a // b (floored) and r = a % b, with 0 ≤ |r| < |b| and r carrying the sign of b
Amortised list append: with growth factor g, total elements copied over n appends ≈ n/(g − 1) → O(1) per append (g = 2 gives n copies; CPython's g ≈ 1.125 gives ≈ 8n, still constant per append)
Naive string building in a loop: total characters copied = 1 + 2 + … + n ≈ n²/2 → O(n²); "".join(parts) is O(n)
Dict/set average lookup cost = O(1) with load factor kept ≤ 2/3; worst case O(n) when all keys collide

Example 1 - slicing arithmetic. s = "ABCDEFGHIJ" (indices 0-9).

Example 2 - integer and float arithmetic traps.

Example 3 - cost of string concatenation. Build a 100,000-character string one character at a time.

parts = [chr(65 + i % 26) for i in range(100_000)]
s = "".join(parts)            # O(n)

Example 4 - aliasing, shallow copy and the mutable default.

grid = [[0] * 3] * 3          # 3 references to ONE row
grid[0][0] = 1
print(grid)                   # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
good = [[0] * 3 for _ in range(3)]   # 3 independent rows

def add(x, bag=[]):           # default created ONCE
    bag.append(x); return bag
print(add(1), add(2))         # [1, 2] [1, 2]  - shared list

def ok(x, bag=None):
    bag = [] if bag is None else bag
    bag.append(x); return bag
print(ok(1), ok(2))           # [1] [2]

grid[0] is grid[1] → True in the first case, False in good.

Example 5 - counting and sorting (typical placement question). Sentence: "data is the new oil and data is everywhere" → 9 words, 7 unique.

from collections import Counter
text = "data is the new oil and data is everywhere"
c = Counter(text.split())
top = sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))
TypeMutableOrderedHashableTypical use
listYesYesNoordered collection you modify
tupleNoYesYes (if items are)fixed record, dict key, multiple return
setYesNoNomembership tests, de-duplication
frozensetNoNoYesset used as a dict key
dictYesInsertion order (3.7+)Nokey → value mapping, JSON
strNoYesYestext

Where it is used

Interview questions

Common mistakes

Related topics

Object-oriented programming concepts · Exception handling and debugging · Functional programming basics · JavaScript essentials · Data structures with Python · Databases and SQL basics

Open in the Knowledge reader →Find jobs →