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

Updated 6 Sep 20266 min read

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

str

"GATE"

Text sequence

Yes

By position

Yes

No

Text

list

[18, 21, 18]

Changeable sequence

Yes

By position

Yes

Yes

Ordered data that changes

tuple

(4, 7)

Fixed sequence

Yes

By position

Yes

No

Fixed record

set

{"python", "gate"}

Unique membership

No positional order

No

Removed

Yes

Membership and uniqueness

dict

{"Asha": 82, "Ravi": 75}

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.

Decision figure comparing Python str, list, tuple, set and dict by order, indexing, duplicates and mutability.

2. Python strings: indexing, slicing, methods and immutability

For word = "PYTHON", indexing and slicing give exact, predictable results:

python
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:

python
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:

python
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:

python
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:

python
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:

  1. words becomes ['gate', 'gate', 'python', 'collections', 'python', 'gate', 'strings'].

  2. sorted(unique) is ['collections', 'gate', 'python', 'strings'].

  3. Counting produces {'gate': 3, 'python': 2, 'collections': 1, 'strings': 1}.

  4. counts.items() supplies pairs; negative count ranks higher frequencies first, then words break ties alphabetically.

  5. ranked is [('gate', 3), ('python', 2), ('collections', 1), ('strings', 1)].

  6. 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.

Pipeline turning a sentence into a word list, unique set, count dictionary and ranked list of tuples.

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

O(1)

Slice k elements into a new result

O(k)

Scan membership in a list, tuple or string

O(n)

Dictionary-key or set membership

Average O(1)

Sort n items

O(n log n)

Join text totalling n characters

O(n)

Choose behaviour before cost, and watch these traps:

  • Trap: items = items.sort() makes items become None. Call items.sort() or use items = sorted(items).

  • Trap: matrix_copy = matrix.copy() leaves nested lists shared. Copy each row when they must be independent.

  • Trap: absent counts["java"] raises KeyError. Use counts.get("java", 0) when zero is the default.

  • Trap: set([3, 1, 3]) is not promised to display sorted. Use sorted(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:

python
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.