Python Collections and Strings: Complete Guide with a Worked Word Counter
Choose the right built-in Python container, trace aliases and slices correctly, and combine all five types in a worked word-counting pipeline.
KnowledgeGate Team
Exam prep & CS education

Python containers look similar but differ on duplicates, order and alias mutation. The built-in str, list, tuple, set and dict types solve the core text, sequence, uniqueness and mapping problems, while the separate collections module provides specialised containers such as Counter and deque. A word-counting pipeline makes the five built-ins concrete by moving from text to an ordered word list, unique values, a key-to-count mapping and ranked pairs.
1. Python collections and strings: choose by behaviour, not syntax
Choose a type by the rule your data must obey.
Type | Example | Logical model | Ordered? | Indexed? | Duplicates | Mutable? | Best use |
|---|---|---|---|---|---|---|---|
|
| Text sequence | Yes | By position | Yes | No | Text |
|
| Changeable sequence | Yes | By position | Yes | Yes | Ordered data that changes |
|
| Fixed sequence | Yes | By position | Yes | No | Fixed record |
|
| Unique membership | No positional order | No | Removed | Yes | Membership and uniqueness |
|
| Key-to-value mapping | Insertion order | By key, not position | Keys are unique | Yes | Lookup by key |
Strings, lists and tuples are ordered sequences. Dictionaries preserve insertion order but use keys; sets are not positional. Use strings for text, lists for changing ordered data, tuples for fixed records such as (4, 7), sets for uniqueness, and dictionaries for key-to-value lookup. The Coding and Skill Development Courses page places these foundations in a wider programming path.

2. Python strings: indexing, slicing, methods and immutability
For word = "PYTHON", indexing and slicing give exact, predictable results:
word[0] # "P"
word[-1] # "N"
word[1:5] # "YTHO"
word[1:5:2] # "YH"
word[::-1] # "NOHTYP"A slice is half-open, excluding position 5 from word[1:5]; word[::-1] reverses the sequence. word[10] raises IndexError, but word[1:10] returns "YTHON".
String methods create new strings:
raw = " Gate AI "
clean = raw.strip().lower().replace(" ", "-")Now raw == " Gate AI " and clean == "gate-ai": immutability leaves the original unchanged. Both "gate" + "-" + "python" and "-".join(["gate", "python"]) produce "gate-python"; join is clearer for many parts. See Lexical Analysis in Compiler Design: Tokens and Lexemes for the character-stream-to-token connection.
3. Python lists and tuples: mutation, aliasing and fixed records
Consider three names and two list objects:
marks = [18, 21, 16]
alias = marks
copy_marks = marks.copy()
alias.append(20)Both marks and alias are now [18, 21, 16, 20]; copy_marks remains [18, 21, 16]. Assignment shares the list; copy() duplicates only its outer layer.
A tuple suits a fixed record. With point = (4, 7), x, y = point gives x = 4 and y = 7; point[0] = 5 raises TypeError. In record = ("Asha", [18, 21]), only the tuple's references are fixed, so record[1].append(20) validly changes the nested list to [18, 21, 20].
Slicing also creates a new outer list. first_two = marks[:2] gives [18, 21]; after first_two[0] = 99, it is [99, 21] while marks stays [18, 21, 16, 20]. Nested objects remain shared.
4. Python sets and dictionaries: uniqueness, membership and mapping
Given names = ["Asha", "Ravi", "Asha", "Meera"], set(names) removes the repeat. Use sorted(set(names)) == ["Asha", "Meera", "Ravi"] for deterministic display.
For python = {"Asha", "Ravi", "Meera"} and sql = {"Ravi", "Kabir"}, sorted(python & sql) is ["Ravi"], the union contains four names, and sorted(python - sql) is ["Asha", "Meera"].
Now keep the best score for each name:
records = [('Asha', 82), ('Ravi', 75), ('Asha', 91), ('Meera', 75)]
best = {}
for name, score in records:
best[name] = max(score, best.get(name, score))The dictionary is {'Asha': 91, 'Ravi': 75, 'Meera': 75} in first-insertion order. sorted(best.items(), key=lambda pair: (-pair[1], pair[0])) gives [('Asha', 91), ('Meera', 75), ('Ravi', 75)]. Assignment overwrites a key; get supplies a fallback.
Remember: {} creates an empty dictionary, while set() creates an empty set. bad = {[1, 2]: "pair"} raises TypeError because a list is unhashable; {(1, 2): "pair"} is valid because its tuple values are hashable.
5. Python collections worked example: count and rank words
This program normalises text, counts words, ranks them, and builds one summary:
text = "Gate gate Python collections python GATE strings"
words = text.lower().split()
unique = set(words)
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
ranked = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
summary = ", ".join(f"{word}:{count}" for word, count in ranked)
print(summary)Trace the result:
wordsbecomes['gate', 'gate', 'python', 'collections', 'python', 'gate', 'strings'].sorted(unique)is['collections', 'gate', 'python', 'strings'].Counting produces
{'gate': 3, 'python': 2, 'collections': 1, 'strings': 1}.counts.items()supplies pairs; negative count ranks higher frequencies first, then words break ties alphabetically.rankedis[('gate', 3), ('python', 2), ('collections', 1), ('strings', 1)].The exact output is
gate:3, python:2, collections:1, strings:1.
The input and summary are strings; words and ranked are lists; each ranked pair is a tuple; unique is a set; and counts is a dictionary.

6. Python collection complexity and traps that change the answer
These normal built-in costs use n for input size and k for slice length.
Operation | Time cost |
|---|---|
Index a list, tuple or string |
|
Slice |
|
Scan membership in a list, tuple or string |
|
Dictionary-key or set membership | Average |
Sort |
|
Join text totalling |
|
Choose behaviour before cost, and watch these traps:
Trap:
items = items.sort()makesitemsbecomeNone. Callitems.sort()or useitems = sorted(items).Trap:
matrix_copy = matrix.copy()leaves nested lists shared. Copy each row when they must be independent.Trap: absent
counts["java"]raisesKeyError. Usecounts.get("java", 0)when zero is the default.Trap:
set([3, 1, 3])is not promised to display sorted. Usesorted(set([3, 1, 3])) == [1, 3].
For another mutability trace, start with data = [1, 2], alias = data, and snapshot = tuple(data), then run alias += [3]. Now data == [1, 2, 3], alias == [1, 2, 3], and snapshot == (1, 2). In-place extension reaches the shared list; the tuple snapshot stays unchanged.
7. How GATE-style reasoning and interviews test Python collections
The completed-cycle GATE 2026 Computer Science syllabus from IIT Guwahati lists Programming in C in Section 4, so Python syntax is not presented as an official GATE CS requirement. Sequence, aliasing, search-cost and data-structure reasoning still transfer; follow the relevant official syllabus.
For an interview-style trace, run:
items = ["gate", "python"]
alias = items
snapshot = tuple(items)
alias[0] = alias[0].upper()
print(items, snapshot)The exact output is ['GATE', 'python'] ('gate', 'python'). The alias changed the list; the tuple retained the original immutable strings. Practise container choice, slices, aliasing bugs, frequency counts, order-preserving deduplication and membership costs.
Data Structures MCQs offers broader practice. KnowledgeGate also has over 130 questions available for practice under Python Collections & Strings: practice depth, not a GATE attribution.
8. Python collections and strings: short version and next step
Strings hold immutable text.
Lists are changeable ordered sequences.
Tuples are fixed ordered records.
Sets model uniqueness and membership.
Dictionaries map unique hashable keys to values.
Aliases share mutable objects unless an intentional copy is made.
For a final self-check, use "set list set tuple list set dict". The pipeline must produce set:3, list:2, dict:1, tuple:1. Predict words, sorted(unique), counts and ranked first.
For a wider sequence, use the Python Course: Concepts, MCQs and Coding. For mixed-language rounds, try Coding for Placements: C, C++, Java and Python. First explain every type chosen in the pipeline.
Keep learning

Pandas Basics in Python: Build, Clean and Analyse a DataFrame Step by Step
Follow one student dataset from its first DataFrame to a clean city summary, while learning how selection, missing values and vectorised calculations really work.

Python Operators and Expressions: Precedence, Types and Worked Output Traces
Trace Python expressions without guessing. This guide connects operator families, precedence, types, short-circuiting and exact output through worked examples.

CSV Files Explained: Parsing Rules, Worked Records and Exam Traps
Learn why commas and newlines are not always boundaries, trace a quote-aware parser, validate text fields with a schema, and calculate processing costs.

Polymorphism and Dunder Methods in Python: Runnable Examples and Exercises
See how one Python operation supports different types, then build a Vector2D class with readable output, addition, magnitude and equality. Includes runnable code, protocol failures and exercises.