Skip to main content

Python Data Structures: Beyond the Basics

Welcome to your next step in Python! While primitive data types (like integers, floats, and strings) hold a single value, Python has built-in complex data types that allow you to store, organize, and manipulate collections of data efficiently.

Let's explore the four main complex data types: Lists, Tuples, Dictionaries, and Sets.


1. Lists

A list is an ordered, mutable (changeable) collection of items. Lists can contain items of different data types and allow duplicate values. They are the most common and versatile data structure in Python.

Key Characteristics:

  • Ordered: Maintains the exact order in which you add items.
  • Mutable: You can add, remove, or change items after creation.
  • Syntax: Created using square brackets [].

Example:

Python Sandbox

2. Tuples

A tuple is very similar to a list, but it is immutable. Once a tuple is created, you cannot change, add, or remove items. They are perfect for data that should never change (like fixed coordinates or configurations).

Key Characteristics:

  • Ordered: Maintains insertion order.
  • Immutable: Unchangeable after creation.
  • Syntax: Created using parentheses ().

Example:

Python Sandbox

3. Dictionaries (Dicts)

A dictionary is a collection of key-value pairs. Instead of using numbers to access elements (like finding the 1st item in a list), you use unique keys (like looking up a word in a real dictionary to find its definition).

Key Characteristics:

  • Key-Value Pairs: Stores data as key: value.
  • Mutable: You can add, remove, or change pairs.
  • Syntax: Created using curly braces {} with colons separating keys and values.

Example:

Python Sandbox

4. Sets

A set is an unordered collection of unique items. Sets are highly efficient for checking if an item exists and for ensuring there are absolutely no duplicate values in your data.

Key Characteristics:

  • Unordered: No guaranteed order and no indexing (you can't ask for the "first" item).
  • Unique: No duplicate values allowed.
  • Syntax: Created using curly braces {} or the set() function.

Example:

Python Sandbox

Lesson Review Test

Test your understanding of the concepts covered above!

  1. Which data type is immutable (cannot be changed after creation)?
    • A) List
    • B) Tuple
    • C) Dictionary
    • D) Set
  2. Which data type uses key: value pairs?
    • A) List
    • B) Tuple
    • C) Dictionary
    • D) Set
  3. What will be the output of the following code?
    my_set = {10, 10, 20, 30}
    print(len(my_set))
    • A) 2
    • B) 3
    • C) 4
    • D) Error
  4. True or False: A list is created using square brackets [].

(Answers: 1. B, 2. C, 3. B (duplicates are removed, so the set is 30 which has 3 items), 4. True)


📚 Deep Dive

Ready to learn more? Check out these excellent resources: