All notes

Programming in Python for GATE DA

GATE DA170 min read

Free preview: 28% of the note

GATE DA asks you to predict the output of short Python programs and to reason about their cost. These notes cover the semantics that such questions test.

Values, names and mutability

In Python a variable is a name bound to an object. Assignment never copies the object; it binds another name to the same one.

TypeMutable?Example
int, float, bool, str, tuple, frozensetno5, "hi", (1, 2)
list, dict, set, user-defined objectsyes[1, 2], {"a": 1}

Example 1: aliasing.

a = [1, 2, 3]
b = a          # b names the same list
b.append(4)
print(a)       # [1, 2, 3, 4]
b = [9]        # rebinding b does not touch a
print(a)       # [1, 2, 3, 4]

== compares values. is compares identity. [1] == [1] is True, but [1] is [1] is False: these are two different lists.

Immutable means the object cannot change. You can still rebind the name.

s = "hello"
t = s.upper()   # a new string; s is unchanged
s += "!"        # binds s to a new string "hello!"
# s[0] = "H"    would raise TypeError: strings do not support item assignment

A tuple can hold a mutable object.

t = ([1], 2)
t[0].append(3)
print(t)        # ([1, 3], 2): the list inside changed
# t[0] = 5      would raise TypeError: the tuple itself cannot change

Shallow and deep copies

import copy
a = [[1, 2], [3, 4]]
b = a.copy()           # shallow: a new outer list, the same inner lists
b[0][0] = 9
b.append([5])
print(a)               # [[9, 2], [3, 4]]: the inner change shows, the append does not
c = copy.deepcopy(a)   # fully independent copy

The [[0] * 3] * 3 trap.

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

Numbers and operators

ExpressionValueWhy
7 / 23.5true division always gives a float
7 // 23floor division
-7 // 2-4floors towards −∞-\infty, not towards 0
-7 % 32the result takes the divisor's sign: −7=3(−3)+2-7 = 3(-3) + 2
7 % -3-27=(−3)(−3)+(−2)7 = (-3)(-3) + (-2)
2 ** 101024power
2 ** -10.5
round(2.5), round(3.5)2, 4rounds half to even
0.1 + 0.2 == 0.3Falsebinary floating point
int("42") + 143
int(3.9), int(-3.9)3, -3truncates towards 0

The identity (a // b) * b + a % b == a always holds.

Integers have unlimited size. 2 ** 100 is exact, so overflow never happens.

Boolean operators return one of their operands, and they short-circuit:

  • 0 or "a" is "a", and "x" or 1/0 is "x": the division never runs.
  • [] and 5 is [], and None or 0 is 0.
  • Falsy values are 0, 0.0, "", [], {}, set(), None and False. Everything else is truthy.

Comparisons chain. 1 < x < 5 means 1 < x and x < 5.

Sequences: strings, lists and tuples

Indexing and slicing. s[start:stop:step] includes start and excludes stop. Negative indices count from the end.

s = "abcdefg"
s[1:5]      # 'bcde'
s[1:5:2]    # 'bd'
s[-3:]      # 'efg'
s[::-1]     # 'gfedcba'
s[5:1:-1]   # 'fedc'
s[10:]      # '' (slices never raise IndexError)

range. range(10, 0, -3) gives 10, 7, 4, 1. range(5) gives 0 to 4, and len(range(2, 11, 3)) is 3 (the values 2, 5, 8).

Common list operations and their cost (for a list of length nn):

You have read the free 28% of this note

Sign in with Google to keep reading. It is free, takes one tap, and you also get:

  • 8 practice questions from this note
  • Every note in full, plus the PDF library
  • Official past papers as timed tests, with explanations
  • An AI tutor for doubts, in Hindi or English
  • Your progress, mistakes and study plan saved on every device
Continue reading, free