∑GATE DA Atlas

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.

Section 411 practice 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.

Python
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; is compares 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 += y mutates 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

ExpressionValueNote
7 / 23.5true division always gives a float
7 // 2, -7 // 23, -4floor division (rounds towards −∞-\infty)
7 % 3, -7 % 3, 7 % -31, 2, -2result takes the sign of the divisor
2 ** 10, 2 ** -11024, 0.5
round(2.5), round(3.5)2, 4banker's rounding (to even)
0.1 + 0.2 == 0.3Falsebinary floating point
int(-3.7)-3truncates towards 0
True + True2bool 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).

Python
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

TypeLiteralOrderedMutableDuplicatesTypical cost
list[1, 2]yesyesyesindex O(1)O(1), append O(1)O(1) amortised, insert/delete at front O(n)O(n), in O(n)O(n)
tuple(1, 2), (1,)yesnoyeslike list, read-only
dict{"a": 1}insertion orderyesunique keysget/set/in O(1)O(1) average
set{1, 2}, set()noyesnoadd/in O(1)O(1) average
dequedeque()yesyesyesappend/pop at both ends O(1)O(1)

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, O(nlog⁡n)O(n\log n)).

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

Python
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 * 2 is 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 declared global or nonlocal.
  • 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 O(φn)O(\varphi^n) 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

Python
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

Python
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.

Q1MCQ1 mark

What does this program print?

Python
a = [1, 2, 3]
b = a
b.append(4)
print(a)
Q2NAT2 marks

What does this program print?

Python
def f(x, acc=[]):
    acc.append(x)
    return len(acc)

f(1)
f(2)
print(f(3))
Q3MCQ1 mark

What does print(7 // -2, -7 % 3) output?

Q4NAT2 marks

What does this program print?

Python
print(sum([i * j for i in range(3) for j in range(i)]))
Q5MCQ2 marks

What does this program print?

Python
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
Q6MCQ1 mark

With s = "GATE2027", what does print(s[1:6:2]) output?

Q7MSQ1 mark

Which of the following Python types are immutable?

One or more options are correct.

Q8NAT2 marks

What does this program print?

Python
def g(n):
    if n <= 1:
        return 1
    return g(n - 1) + g(n - 2)

print(g(6))
Q9MCQ2 marks

What does this program print?

Python
def gen():
    for i in range(3):
        yield i * i

g = gen()
print(next(g) + next(g) + sum(g))
Q10NAT2 marks

What does this program print?

Python
d = {}
for w in "the cat and the hat".split():
    d[w] = d.get(w, 0) + 1
print(len(d) * d["the"])
Q11MCQ2 marks

What does this program print?

Python
x = 10
def f():
    x = 5
    def g():
        nonlocal x
        x += 1
        return x
    return g() + x

print(f(), x)