GATE DA · Programming, Data Structures and Algorithms
Programming in Python
Core Python for GATE DA: types and mutability, operators, slicing, references and aliasing, loops and comprehensions, functions and recursion, and tracing short snippets to predict their output.
Before you start
Basic programming ideas
Variables, conditions and loops are assumed; Python only changes the syntax and a few rules.
Integer division and remainders
Python's // and % round towards minus infinity, which changes answers for negative numbers.
Every value in Python is an object with a type. The types GATE uses:
Type
Example
Mutable?
Ordered?
int, float, bool
7, 2.5, True
No
–
str
"gate"
No
Yes
tuple
(1, 2)
No
Yes
list
[1, 2]
Yes
Yes
dict
{"a": 1}
Yes
Keeps insertion order
set
{1, 2}
Yes
No
Immutable objects cannot be changed after creation: s[0] = "x" on a string raises TypeError. Dictionary keys and set elements must be hashable, so a list cannot be a key, but a tuple of numbers can.
Operators to watch:
/ always gives a float: 7 / 7 is 1.0.
// is floor division and % takes the sign of the divisor: -7 // 2 is -4 and -7 % 2 is 1. They always satisfy a == (a // b) * b + a % b.
** is right-associative: 2 ** 3 ** 2 is 2 ** 9 = 512.
== compares values; is checks whether two names refer to the same object. [1, 2] == [1, 2] is True but [1, 2] is [1, 2] is False.
bool is a subtype of int: True + True is 2.
and / or short-circuit and return one of the operands, not necessarily True/False: 0 or 5 is 5.
2. Indexing and slicing
Strings, lists and tuples are sequences. Index 0 is the first item and -1 the last.
A slicea[start:stop:step] takes items from start up to but not includingstop, moving by step.
Missing start/stop mean "from the beginning"/"to the end" in the direction of step.
With a negative step the slice walks backwards, so start should be the larger index: a[::-1] reverses.
Slices never raise IndexError; out-of-range bounds are clipped. A single index out of range does raise it.
Useful list methods: append(x) adds one item, extend(seq) adds each item, insert(i, x), pop() removes and returns the last item, pop(i) the item at i, remove(x) the first x. a.sort() sorts in place and returns None; sorted(a) returns a new list. Both accept key= and reverse=True.
To trace a slice quickly, list the indices first (1, 3 for a[1:5:2]), then read the values.
3. Names, references and aliasing
A Python variable is a name bound to an object. Assignment b = a does not copy; it makes b refer to the same object. For a mutable object, a change through one name is seen through the other. This is aliasing.
b += [3] on a list mutates it in place (same object).
b = b + [3] builds a new list and rebinds b; a is unchanged.
For an immutable object (int, str, tuple) += always builds a new object.
a[:], list(a) and a.copy() make a shallow copy: a new outer list whose items are the same objects. copy.deepcopy(a) copies nested objects as well.
[[0] * 3] * 3 makes three references to one inner list, so setting m[0][1] = 5 changes every row. Use [[0] * 3 for _ in range(3)] instead.
A tuple is immutable, but a list inside it can still change: t = (1, [2]); t[1].append(3) is allowed.
Function arguments are passed by object reference: the parameter is a new name for the caller's object. Mutating it (L.append) is visible to the caller; rebinding it (L = []) is not.
Two names, one list: assignment copies the reference, not the list
4. Loops, range and comprehensions
range(start, stop, step) produces integers from start up to but not including stop. range(10, 0, -3) gives 10, 7, 4, 1. The number of values in range(0, n, k) for positive k is .
for x in seq: visits each item; enumerate(seq) gives (index, item) pairs; zip(a, b) pairs items and stops at the shorter sequence.
break leaves the loop; continue skips to the next iteration.
A while loop runs while its condition is true; trace it with a table of variable values per iteration.
A comprehension builds a collection in one expression:
sq = [x * x for x in range(10) if x % 3 == 0] # [0, 9, 36, 81]
pairs = [i * j for i in range(1, 4) for j in range(i)]
# outer loop first: [0, 0, 2, 0, 3, 6]
freq = {c: "banana".count(c) for c in "banana"}
# {'b': 1, 'a': 3, 'n': 2}
In a comprehension with two for clauses the left one is the outer loop, exactly as in nested loops. Set comprehensions use {} without a colon; dict comprehensions use key: value.
Counting pattern: d[k] = d.get(k, 0) + 1. d.get(k, 0) returns 0 if the key is missing instead of raising KeyError.
5. Functions, scope and recursion
def f(x, y=2): defines a function with a default argument. Defaults are evaluated once, when def runs. A mutable default such as L=[] is therefore shared across calls:
A function without a return statement returns None.
Scope (LEGB): a name is looked up in the Local function, then Enclosing functions, then Global (module), then Built-ins. Assigning to a name inside a function makes it local unless declared global (or nonlocal for an enclosing function). Reading a global before assigning to it in the same function raises UnboundLocalError.
Recursion: trace with a call tree. Statements before the recursive call run on the way down; statements after it run on the way back up, in reverse order. A function with two recursive calls, like fib(n - 1) + fib(n - 2), makes an exponential number of calls.
lambda x: x * x is a one-expression anonymous function, often passed as key= to sorted, max or min. sorted is stable: items with equal keys keep their original order.
Formulas to remember
Floor division identityPython's `%` result has the sign of
Length of a range
Slice indices
Common mistakes
Treating // as truncation: -7 // 2 is -4, not -3, and -7 % 2 is 1.
Including the stop index in a slice or range: a[1:4] and range(1, 4) stop before 4.
Assuming b = a copies a list; it only adds a second name for the same object.
Forgetting that a mutable default argument is shared between calls.
Writing x = a.sort() and expecting a list; sort returns None.
Building a 2D list with [[0] * n] * n, which repeats one inner list.
Step 1: Convert the negative indices of a[-4:-1] first.
Try it on paper first.
Example 2: Aliasing with += and +
conceptual
What does this print?
x = [1, 2]
y = x
x += [3]
z = x
x = x + [4]
print(x, y, z)
Step 1: After y = x, how many list objects are there?
Try it on paper first.
Example 3: Tracing recursion with work before and after the call
numerical
What does this print?
def r(n):
if n <= 0:
return 0
print(n, end=" ")
r(n - 2)
print(n, end=" ")
r(5)
Step 1: Write the chain of calls.
Try it on paper first.
Example 4: Grouping anagrams with a dictionary
numerical
What does this print?
words = ["listen", "silent", "enlist", "google", "banana", "gogole"]
d = {}
for w in words:
k = "".join(sorted(w))
d[k] = d.get(k, 0) + 1
print(max(d.values()), len(d))
Step 1: What is the key for each word?
Try it on paper first.
Previous year questions
10 official GATE DA questions on this topic, newest first.
10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.
Mark as mastered
Loading your progress…
My revision notes
Notes written by the GATEiit team against the official GATE DA syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.