TutreNews Learn

Python Data Structures: Lists, Dictionaries, Sets and Tuples

Organise data in Python: list operations, slicing and comprehensions, dictionaries for lookup and counting, sets for uniqueness and set algebra, tuples and unpacking, and how to choose the right structure. Every code example is executed and verified.

Beginner · 3 units · 10 lessons · 91 exercises · ~1.7 h

What you will learn

  • Create, index, slice and modify lists and know which methods change them in place
  • Write list and dictionary comprehensions
  • Use dictionaries for lookup, counting and grouping
  • Use sets to remove duplicates and combine collections with set operators
  • Unpack tuples and return several values from a function
  • Avoid aliasing and shallow-copy bugs and choose the right structure for a task

Prerequisites

  • Python fundamentals: variables, conditions, loops and functions

Learning path

1 Lists

  1. Lists, indexing and slicing9 min · 6 exercises
  2. List methods and mutability11 min · 7 exercises
  3. Looping and list comprehensions11 min · 7 exercises
  4. Unit exam6 exercises

2 Dictionaries and sets

  1. Dictionaries10 min · 6 exercises
  2. Counting, grouping and comprehensions12 min · 7 exercises
  3. Sets10 min · 7 exercises
  4. Unit exam6 exercises

3 Tuples, copies and choosing the right structure

  1. Tuples and unpacking9 min · 6 exercises
  2. Copies, aliasing and mutable pitfalls11 min · 6 exercises
  3. Choosing the right structure9 min · 6 exercises
  4. Putting it together: inventory and word statistics12 min · 6 exercises
  5. Unit exam6 exercises
  1. Final exam9 exercises

Practical project: A contact-book and word-statistics toolkit

  1. Contact book: store contacts as a dictionary from name to a record (a dictionary with phone, city and a list of tags). Write functions add_contact, find_by_city (returns names, sorted) and all_tags (returns the set of all tags used).
  2. Word statistics: read a paragraph (type or paste one of at least 100 words). Count the words (lower case, without punctuation) with a dictionary; print the 5 most common words, the number of different words and the longest word.
  3. Set questions: ask two lists of tags from two people and print the shared tags, the tags only person A has, and the tags that exactly one person has.
  4. Tuples: write min_max_avg(numbers) returning a tuple, and a function that returns the 3 contacts closest to a given (x, y) location, with locations stored as tuples.
  5. Bug hunt: deliberately create two bugs (a shared default list and a shallow-copy problem), explain each in a comment and fix it.
  6. Write at least 10 test calls with expected results, including an empty input, and print a pass/fail summary.

References

Related courses