Difficulty: Beginner to Intermediate | Prerequisites: Basic Python syntax, variables, loops, conditionals.
This topic covers Python's core built-in data types: strings, lists, dictionaries, sets, and tuples. These are the building blocks for nearly every program you will write in CS303E, from simple text processing to file I/O and class design. You should already be comfortable with basic Python syntax, including variables, loops, and conditionals. If terms like "mutable" or "immutable" are new to you, start here before moving on to classes or recursion.
Python gives you several built-in collection types, each with different rules about what you can store and how you can change it. Strings and tuples are immutable (you cannot modify them after creation), while lists, dictionaries, and sets are mutable. Knowing which operations are valid on which type, and what happens when you pass a mutable object to a function, is the core of this material.
Immutable
An object whose value cannot be changed after it is created. Strings and tuples are immutable in Python. In simple terms, once you make one, you are stuck with it as-is; you can only create a new one.
Mutable
An object whose value can be changed in place after creation. Lists, dictionaries, and sets are mutable. Think of it as a container you can open up and rearrange without replacing the container itself.
String
An immutable sequence of characters, created with quotes ("hello"). Every string in Python is an object. In simple terms, it is a piece of text you can read and slice but never edit in place.
List
A mutable, ordered sequence of elements, created with square brackets ([1, 2, 3]). Lists support indexing, slicing, appending, sorting, and more. Think of it as a row of boxes you can rearrange or swap out at will.
Dictionary (dict)
A mutable, unordered collection of key-value pairs, created with curly braces ({"a": 1}). Keys must be unique and immutable; values can be anything. In simple terms, it is a lookup table: give it a key, get back a value.
Set
A mutable, unordered collection of unique elements, created with curly braces ({1, 2, 3}) or set(). Sets do not support indexing. Think of it as a bag where duplicates are automatically thrown out.
Tuple
An immutable, ordered sequence of elements, created with parentheses ((1, 2)) or just commas. In simple terms, it is a list you cannot change.
Sequence
An ordered collection that supports indexing and slicing. Strings, lists, and tuples are all sequences.
Object
In Python, everything is an object: integers, strings, lists, functions, classes. Every value has a type, an identity, and a value.
Name mangling (double-underscore prefix)
Attributes beginning with two underscores (e.g. self.__score) are name-mangled by Python to make them harder to access from outside the class. These are called private attributes. In simple terms, the double underscore tells other programmers "hands off, this is internal."
Strings are sequences of characters. They are immutable: you cannot assign to an index (e.g. s[0] = 't' raises a TypeError).
To "change" a string, you create a new one (concatenation, slicing, replace(), etc.).
"Hello" is an object in Python. So is every other value.
Indexing and slicing
s[i] returns the character at position i.
s[-10::2] means start 10 from the end, step by 2.
s[:len(s)//2] gives the first half of an even-length string.
split() vs split(" ")
These are not the same. s.split() with no argument splits on any whitespace and discards empty strings from the result. s.split(" ") splits only on single spaces and keeps empty strings. For example, "a b".split() returns ['a', 'b'], but "a b".split(" ") returns ['a', '', 'b'].
lstrip(), rstrip(), strip()
Remove leading, trailing, or both leading and trailing whitespace (including \n).
rindex(sub)
Returns the highest index where the substring sub is found. Raises ValueError if not found.
String comparisons
Comparisons between characters are done by comparing their underlying ASCII/Unicode codes. Uppercase letters have lower codes than lowercase letters, so "BANANA" < "Alabama" is True (uppercase B = 66 comes before lowercase letters). The comparison "wow" >= "wow wow" evaluates to False because "wow" is a prefix of "wow wow" and is shorter.
Repetition
s * 100 repeats the string s one hundred times.
Lists are mutable. You can assign to an index (L[0] = 99), append, remove, and sort in place.
Because lists are mutable, passing a list to a function means the function can modify the original list. This is a common source of bugs and exam questions.
2D lists
A two-dimensional list is a list of lists. If L is a non-empty 2D list of integers, then L[0] is a list of integers (not an integer, not None, not a 2D list).
sort() and string sorting
list.sort() sorts in place and returns None. Strings are compared character by character using their ASCII/Unicode values. Uppercase letters come before all lowercase letters, so "BANANA" sorts before "Alabama", which sorts before "ban".
Example: ["banana", "BANANA", "ban", "bandana", "Alabama"].sort() produces ['Alabama', 'BANANA', 'ban', 'banana', 'bandana'].
append() returns None
[2, 5, 1].append(7) modifies the list in place but the expression itself evaluates to None. This trips students up on exams.
Lists are passed by reference
When you pass a list to a function and the function appends to it, the original list outside the function is also changed. This is because both the function parameter and the original variable point to the same list object in memory.
Dictionaries cannot have repeated keys. If you assign to an existing key, the old value is overwritten.
Keys must be immutable (strings, numbers, tuples). Values can be any type.
Access a value with d[key]. Using a key that does not exist raises a KeyError.
d.keys() returns a view of keys. max(d.keys()) returns the largest key (by comparison, so for strings, lexicographic order).
d.values() returns a view of values. To count unique values: len(set(d.values())).
Building dictionaries from data
A common exam pattern is building a dictionary by iterating through a string or list and counting occurrences. If a key is not yet in the dictionary, initialise it to 0 first, then increment.
if s[0] not in res:
res[s[0]] = 0
res[s[0]] += 1Sets are unordered and contain only unique elements. Duplicates are automatically removed.
Sets do not support indexing. c[i] where c is a set and i is a positive integer is never valid.
bool([]) is False. An empty list is falsy, and so is an empty set, empty dict, empty string, 0, and None.
Set operations
s1.issubset(s2): every element of s1 is in s2.
s1.intersection(s2): elements in both. If s1 is a subset of s2, then s1.intersection(s2) == s1 (not s2).
s1.difference(s2): elements in s1 not in s2. If s1 is a subset of s2, then s1.difference(s2) == set() (the empty set).
s1 ^ s2 (symmetric difference): elements in one but not both. {1,2,5} ^ {2,4} gives {1, 4, 5}.
s.add(x): adds x to the set.
s.remove(x): removes x from the set (raises KeyError if absent).
Tuples are immutable, ordered sequences. Created with parentheses (3, 4) or just commas.
Useful for returning multiple values from a function or grouping related data.
A common exam expression: (int(num), int(num) + 1) creates a two-element tuple of the integers immediately below and above a float.
Students often think s.split() and s.split(" ") do the same thing. They do not. The no-argument version collapses consecutive whitespace; the single-space version does not.
Students often think s[0] = 't' will change a string. It will not. Strings are immutable; this raises a TypeError.
Students often think list.append(x) returns the new list. It does not. It returns None and modifies the list in place.
Students often think bool([]) is True because [] is "something." It is not. An empty collection is falsy in Python.
Students often think sets support indexing like lists. They do not. my_set[0] raises a TypeError.
⚠️ Know the difference between split() and split(" "). This appears on exams regularly.
⚠️ Understand mutability: strings and tuples are immutable; lists, dicts, and sets are mutable. You will be asked to trace code that modifies a list inside a function.
⚠️ append(), sort(), add(), and remove() all modify in place and return None.
⚠️ Sets do not support indexing. If a question asks which type does not support c[i], the answer is set.
⚠️ String comparison uses ASCII/Unicode codes. Uppercase letters sort before lowercase. Be ready to predict the output of sort() on a mixed-case list of strings.
⚠️ bool([]) is False. Know which values are falsy.
True or False: "Hello" is an object in Python. → True
True or False: You can change a string by assigning to an index. → False (strings are immutable)
Fill in the blank: Unlike strings, list objects are ______. → mutable
True or False: Dictionaries can have repeated keys. → False
Fill in the blank: bool([]) evaluates to ______. → False
Q: What does "a!!b!cde!".split("!") evaluate to?
A: ['a', '', 'b', 'cde', '']
Q: What does "texas longhorns"[-10::2] evaluate to?
A: 'slnhrs' (start at index -10, which is 's' in 'longhorns', step by 2)
Q: What does max({"A":3, "Z":9, "W":-5}.keys()) evaluate to?
A: 'Z' (max of the keys, compared as strings)
Q: What does {1,2,5} ^ {2, 4} evaluate to?
A: {1, 4, 5} (symmetric difference: elements in one set but not both)
Q: What does [2, 5, 1].append(7) evaluate to?
A: None (append modifies in place, returns nothing)
Q: For which type is c[i] (where i is a positive integer) never valid: list, dict, string, or set?
A: set. Sets do not support indexing.
Q: Write a Python expression for: a list of the squares of all integers 1 through 100.
A: [x**2 for x in range(1, 101)]
Q: Write a Python expression for: the number of unique values in a dictionary d.
A: len(set(d.values()))
Q: Write a Python expression for: a set containing all lowercase vowels in a string s.
A: set(c for c in s if c in 'aeiou') or {c for c in s if c in 'aeiou'}
This connects to file I/O because reading a file line by line often involves splitting strings and building dictionaries or sets from the results. It connects to classes and OOP because class attributes store data in these same types (a dictionary of friends, a set of visitors), and understanding mutability is essential for predicting how methods change an object's state. It also connects to recursion, where you frequently build dictionaries or process strings character by character in the base and recursive cases.
Tags: Python data types, strings, lists, dictionaries, sets, tuples, mutable, immutable, split, lstrip, rstrip, rindex, sort, append, set operations, intersection, union, difference, symmetric difference, issubset, indexing, slicing, ASCII, Unicode, list comprehension, bool, falsy, truthy, CS303E, UT Austin, Dr. Bill Young