Programming in Python
Python as GATE tests it — the object model (names, references, mutability and aliasing), numeric semantics (integer division, modulo, floats), strings and slicing, lists, tuples, dictionaries and sets, comprehensions, functions (default arguments, *args, scope and closures), recursion, iterators and generators, classes, exceptions, and a checklist for output-tracing questions.
GATE DA uses Python for every programming question. The questions are mostly "what does this code print?", so the goal is to know the language's semantics precisely — especially where Python differs from C or Java.
Names, objects and references
Every value is an object; a variable is a name bound to an object. Assignment never copies — it binds another name to the same object.
a = [1, 2, 3]
b = a # same object: a is b → True
c = a[:] # new list (shallow copy): a == c → True, a is c → False
b.append(4) # a is now [1, 2, 3, 4]; c is unchanged
==compares values;iscompares identity.- Mutable objects (list, dict, set) can change in place; immutable ones (int, float, str, tuple, frozenset) cannot — "modifying" them creates a new object.
x += ymutates a list in place but rebinds an int or tuple.- Shallow vs deep copy:
copy.copy(x)copies the outer container; nested objects are shared.copy.deepcopy(x)copies recursively.
Arguments are passed by object reference ("call by sharing"): a function can mutate a mutable argument, but rebinding the parameter name inside the function does not affect the caller.
Numbers
| Expression | Value | Note |
|---|---|---|
7 / 2 | 3.5 | true division always gives a float |
7 // 2, -7 // 2 | 3, -4 | floor division (rounds towards ) |
7 % 3, -7 % 3, 7 % -3 | 1, 2, -2 | result takes the sign of the divisor |
2 ** 10, 2 ** -1 | 1024, 0.5 | |
round(2.5), round(3.5) | 2, 4 | banker's rounding (to even) |
0.1 + 0.2 == 0.3 | False | binary floating point |
int(-3.7) | -3 | truncates towards 0 |
True + True | 2 | bool is a subclass of int |
Integers have arbitrary precision (no overflow). Operator precedence: ** (right-associative: 2**3**2 == 512) > unary - (-2**2 == -4) > * / // % > + - > comparisons > not > and > or. Comparisons chain: 1 < x < 5.
and/or short-circuit and return one of their operands: 0 or "x" is "x", 3 and 0 is 0. Falsy values: 0, 0.0, "", [], {}, set(), None, False.
Strings and slicing
Strings are immutable sequences. Slicing s[start:stop:step] includes start, excludes stop; negative indices count from the end; omitted bounds default to the ends (reversed for negative steps).
s = "dataset"
s[0], s[-1] # 'd', 't'
s[2:5] # 'tas'
s[::-1] # 'tesatad'
s[::2] # 'dtst'
s[10:] # '' — slicing never raises IndexError (indexing does)
Useful methods: split, join, strip, replace, find (−1 if absent) vs index (raises), upper, count, startswith. f-strings: f"{x:.2f}".
Built-in collections
| Type | Literal | Ordered | Mutable | Duplicates | Typical cost |
|---|---|---|---|---|---|
| list | [1, 2] | yes | yes | yes | index , append amortised, insert/delete at front , in |
| tuple | (1, 2), (1,) | yes | no | yes | like list, read-only |
| dict | {"a": 1} | insertion order | yes | unique keys | get/set/in average |
| set | {1, 2}, set() | no | yes | no | add/in average |
| deque | deque() | yes | yes | yes | append/pop at both ends |
Note {} is an empty dict, not a set. list.sort() sorts in place and returns None; sorted(x) returns a new list. Both are stable (Timsort, ).
Comprehensions: [expr for x in it if cond], {k: v for ...}, {x for ...}, and generator expressions (expr for ...). Multiple for clauses nest left to right.
Functions
def f(a, b=2, *args, c, **kwargs): # positional, default, varargs, keyword-only, keyword varargs
...
f(1, c=3) # a=1, b=2, args=(), c=3, kwargs={}
- Default values are evaluated once at definition time (the mutable-default trap).
- Functions are objects: they can be passed, returned and stored.
lambda x: x * 2is an anonymous function. - Scope (LEGB): Local → Enclosing → Global → Built-in. Assigning to a name anywhere in a function makes it local throughout that function (reading it before assignment raises
UnboundLocalError) unless declaredglobalornonlocal. - Closures capture variables by reference (late binding).
Recursion
A recursive function needs a base case and progress towards it. Python's default recursion limit is about 1000 frames and there is no tail-call optimisation. Trace recursive calls with a call tree; count calls with a recurrence (naive Fibonacci makes calls). Memoisation (@functools.lru_cache) turns overlapping subproblems into dynamic programming.
Iterators and generators
An iterable produces an iterator via iter(); next() advances it and StopIteration ends it. A function containing yield returns a generator that runs lazily, pausing at each yield, and can be consumed only once. range, zip, map, filter and enumerate are lazy too.
Classes in brief
class Counter:
count = 0 # class attribute, shared by all instances
def __init__(self, start=0):
self.value = start # instance attribute
Counter.count += 1
def __repr__(self):
return f"Counter({self.value})"
Methods receive the instance as self. Inheritance: class B(A):, super().__init__(...). Special methods (__len__, __eq__, __lt__, __iter__) hook into built-in syntax.
Exceptions
try:
x = int("abc")
except ValueError as e:
x = 0
else:
pass # runs if no exception
finally:
pass # always runs
Common exceptions: IndexError, KeyError, TypeError, ValueError, ZeroDivisionError, AttributeError, RecursionError.
Output-tracing checklist
Quick revision
Practice questions
GATE-style questions: 4 one-mark and 7 two-mark. Wrong MCQs cost ⅓ of their marks in the real exam; MSQ and NAT have no negative marking. Attempt each before opening the solution.
What does this program print?
a = [1, 2, 3]
b = a
b.append(4)
print(a)
What does this program print?
def f(x, acc=[]):
acc.append(x)
return len(acc)
f(1)
f(2)
print(f(3))
What does print(7 // -2, -7 % 3) output?
What does this program print?
print(sum([i * j for i in range(3) for j in range(i)]))
What does this program print?
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
With s = "GATE2027", what does print(s[1:6:2]) output?
Which of the following Python types are immutable?
One or more options are correct.
What does this program print?
def g(n):
if n <= 1:
return 1
return g(n - 1) + g(n - 2)
print(g(6))
What does this program print?
def gen():
for i in range(3):
yield i * i
g = gen()
print(next(g) + next(g) + sum(g))
What does this program print?
d = {}
for w in "the cat and the hat".split():
d[w] = d.get(w, 0) + 1
print(len(d) * d["the"])
What does this program print?
x = 10
def f():
x = 5
def g():
nonlocal x
x += 1
return x
return g() + x
print(f(), x)