1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 1

CAP7004 · Unit 1: Python foundations and analysis

Built-in Python data structures and their costs

8 practice questions

Key points

  • list/dict/set/tuple differ in order, mutability and duplicates
  • dict and set lookups are O(1) on average, list search is O(n)
  • pop(0) and insert(0) on a list cost O(n)
  • Assignment shares references; copy explicitly

Python's built-ins are the data structures you use most.

TypeOrderedMutableDuplicatesTypical use
listYesYesYesSequence, stack
tupleYesNoYesFixed records, dict keys
dictInsertion order (3.7+)YesUnique keysKey-value lookup
setNoYesNoMembership, uniqueness

Average costs (n = size):

  • list: index a[i] O(1), append amortized O(1), pop() O(1), pop(0) and insert(0, x) O(n), x in a O(n).
  • dict and set: lookup, insert, delete average O(1); worst case O(n) with many collisions.
  • Slicing copies: a[i:j] costs O(j - i).

Pitfalls: b = a copies the reference, not the list. [[0]*3]*3 repeats the same inner list three times, so changing one row changes all. list.sort() sorts in place and returns None; sorted() returns a new list. A mutable default argument such as def f(x, l=[]) is created once and shared between calls.

Try two questions

Question 1 · Tier 2, Understand

After a = [1, 2, 3]; b = a; b.append(4), what is a?

  1. [1, 2, 3]
  2. [4, 1, 2, 3]
  3. [1, 2, 3, 4]
  4. An error is raised
Show the answer

C. b and a refer to the same list object, so the change is visible through both names.

Question 2 · Tier 4, Analyse

def f(x, l=[]): l.append(x); return l. After f(1), the call f(2) returns:

  1. [2, 1]
  2. [1, 2]
  3. [1]
  4. [2]
Show the answer

B. The default list is created once at definition time and reused across calls.