No history yet

Introduction to Python Data Structures

Organizing Your Data

In programming, you're always working with data. It could be a list of user names, settings for an application, or coordinates on a map. Just like you wouldn't toss all your important papers into one big pile, you need ways to organize your data in code. Python gives you four fundamental tools for this: lists, tuples, dictionaries, and sets. Each one is a type of container, or data structure, designed for a different job.

Lists: Ordered and Changeable

A list is the most basic and flexible data structure. Think of it as a shopping list. It's an ordered collection of items, and you can add, remove, or change things on the fly. In Python, you create a list by putting items inside square brackets [], separated by commas.

# A list of grocery items
groceries = ["milk", "bread", "eggs"]
print(groceries)

Since lists are ordered, each item has a position, or index. The first item is at index 0, the second is at index 1, and so on. You can grab a specific item by using its index.

# Access the first item (at index 0)
first_item = groceries[0]
print(first_item)  # Output: milk

Because lists are mutable (changeable), you can also update an item or add a new one.

# I bought the wrong bread!
# Let's change the second item (at index 1)
groceries[1] = "sourdough bread"

# I forgot to add butter
groceries.append("butter")

print(groceries)
# Output: ['milk', 'sourdough bread', 'eggs', 'butter']

Tuples: Ordered and Unchangeable

A tuple is like a list, but with one crucial difference: once you create it, you can't change it. It's immutable. This is useful for data that should remain constant, like the coordinates for a specific point on a map. You create tuples using parentheses ().

# Coordinates for a fixed point (latitude, longitude)
location = (40.7128, -74.0060)
print(location)

You can access items in a tuple using an index, just like with a list.

# Get the latitude
latitude = location[0]
print(latitude) # Output: 40.7128

But if you try to change an item in a tuple, Python will give you an error. This is a safety feature, protecting the data from accidental changes.

# This will cause an error!
location[0] = 41.8781
# TypeError: 'tuple' object does not support item assignment

The main takeaway: Use a list when you need a collection that can change. Use a tuple when you need one that should never change.

Dictionaries: Unordered Key-Value Pairs

Imagine a real dictionary. You look up a word (a key) to find its definition (a value). Python dictionaries work the same way. They store data in key-value pairs, which makes them perfect for labeling information. Dictionaries are created with curly braces {}.

# A dictionary storing user information
user = {
    "username": "alex",
    "user_id": 101,
    "is_active": True
}
print(user)

Instead of using a numeric index, you access values by using their unique key.

# Get the user's name
name = user["username"]
print(name) # Output: alex

Dictionaries are mutable, so you can easily add new key-value pairs or change existing ones.

# Change the user's active status
user["is_active"] = False

# Add a new piece of information
user["last_login"] = "2023-10-27"

print(user)
# Output: {'username': 'alex', 'user_id': 101, 'is_active': False, 'last_login': '2023-10-27'}

Sets: Unordered and Unique

A set is an unordered collection where every item is unique. Think of it as a bag of unique marbles; you can't have two of the exact same marble. Sets are also created with curly braces {}, but they don't have key-value pairs.

# A set of unique tags for a blog post
tags = {"python", "data", "code", "basics"}
print(tags)

The most important feature of a set is that it automatically handles uniqueness. If you try to add an item that's already there, nothing happens. This makes sets great for removing duplicates from a list.

# A list with duplicate numbers
numbers = [1, 2, 2, 3, 4, 3, 5]

# Convert the list to a set to get unique items
unique_numbers = set(numbers)

print(unique_numbers)
# Output: {1, 2, 3, 4, 5}

Because sets are unordered, you can't access items using an index. Instead, you typically use them to quickly check if an item exists within the set.

# Check if 'python' is in our set of tags
if "python" in tags:
    print("This post is tagged with python!")

Ready to test your knowledge of these fundamental data structures?

Quiz Questions 1/6

Which of the following Python data structures is defined as an ordered, immutable collection of items?

Quiz Questions 2/6

What is the result of the following Python code?

my_set = {1, 2, 3, 3, 2}
print(len(my_set))

Understanding these four data structures is a huge step. They are the building blocks you'll use constantly to manage data in your Python programs.