TutorialsPythonData Structures
Share:

Data Structures

intermediate

Part of Core Python

Theory

Python provides four powerful built-in data structures, each suited to different use cases. Choosing the right one makes your code faster, clearer, and more maintainable.

Lists ([1, 2, 3]) are ordered, mutable sequences. They can contain elements of different types and support indexing, slicing, and methods like append(), insert(), remove(), pop(), sort(), and reverse(). Lists are the most versatile and commonly used data structure.

Tuples ((1, 2, 3)) are ordered, immutable sequences. Once created, they cannot be modified. Tuples are faster than lists and are used for fixed collections, function return values, and dictionary keys. They can be unpacked: a, b, c = my_tuple.

Sets ({1, 2, 3}) are unordered collections of unique elements. They support mathematical set operations: union (|), intersection (&), difference (-), and symmetric difference (^). Use sets for removing duplicates, membership testing, and set logic.

Dictionaries ({"key": "value"}) store key-value pairs. Keys must be immutable (strings, numbers, tuples) and unique. Dictionaries provide O(1) average-time lookups. Methods include keys(), values(), items(), get(), and update(). Python 3.7+ preserves insertion order.

List comprehensions provide a concise way to create lists: [expression for item in iterable if condition]. They replace many for loop patterns with single-line expressions. Dictionary and set comprehensions work similarly.

When to use each:

  • List — ordered collection that needs modification, iteration, or sorting
  • Tuple — fixed data (coordinates, RGB values), function returns, immutable requirements
  • Set — unique items, membership tests, mathematical set operations
  • Dictionary — key-based lookups, mappings, structured data
Data Structures Examples
python
Dictionaries and Comprehensions
python

Exercises

Word Frequency Counter

easy

Write a Python program that takes a list of words and returns a dictionary with each word as a key and its frequency as the value. Use the list: ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'].

Starter Code:

words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']\n# Build frequency dictionary\nprint(freq)

Expected Output:

{'apple': 3, 'banana': 2, 'cherry': 1}

Mini Quiz

Mini Quiz