Dictionary is best to associate names and grades
Data structures are a fundamental concept in programming that allow you to organize and store data efficiently. Python provides several built-in data structures that are flexible, powerful and easy to use. Understanding how and when to use these different data types is key to writing clean, optimized Python code.
In this beginner‘s guide, we‘ll take an in-depth look at Python‘s 4 main built-in data structures:
- Lists
- Tuples
- Dictionaries
- Sets
We‘ll explain what makes each one unique, how to work with them in code, and common scenarios where you would use them. Let‘s dive in!
What are data structures and why are they important?
A data structure is a format for organizing, processing, retrieving and storing data. There are many basic and advanced data structures, all designed to arrange data to suit a specific purpose. Data structures serve as the basis for abstract data types (ADT).
Different types of data structures are suited for different kinds of applications, and some are highly specialized to specific tasks. Choosing the right data structure for a given task requires careful thought and can have a huge impact on the performance of your code. Using the wrong data structure can mean the difference between a program running in milliseconds versus hours.
While advanced data structures exist, mastering the basics first is key. Python‘s built-in data structures are used in almost every program and provide a great starting point for learning.
Lists
Lists are used to store multiple items in a single variable. Lists are:
- Ordered – Items have a defined order that won‘t change
- Changeable – You can change, add, and remove items after creation
- Allow duplicates – Lists can have items with the same value
Creating a list:
fruits = ["apple", "banana", "orange"]
Accessing list elements:
fruits[0] # "apple"
fruits[-1] # "orange"
Modifying a list:
fruits[1] = "pear"
fruits.append("kiwi")
fruits.insert(1, "grape")
fruits.remove("apple")
Some other useful list methods:
- len(fruits) – Get the number of items
- fruits.pop() – Removes the last item
- fruits.clear() – Empties the list
- fruits.sort() – Sorts the list
- fruits.reverse() – Reverses the order
- fruits.count("pear") – Counts occurrences of an item
Lists are incredibly versatile data structures in Python. You‘ll find yourself using them all the time to store collections of related items that may need to be changed.
Tuples
Tuples are used to store multiple items in a single variable. Tuples are:
- Ordered – Items have a defined order
- Unchangeable – You cannot change items after creation
- Allow duplicates – Tuples can have items with the same value
Creating a tuple:
fruits = ("apple", "banana", "orange")
Accessing tuple elements is the same as lists:
fruits[0] # "apple"
The key difference is that tuples are immutable – you cannot add, change or remove items after creation. Trying to modify a tuple will raise an error:
fruits[1] = "pear" # TypeError!
However, you can convert a tuple to a list, modify it, then convert it back:
fruits = list(fruits)
fruits[1] = "pear"
fruits = tuple(fruits)
Tuples have fewer methods than lists, but you can still do:
- len(fruits) – Get the number of items
- fruits.count("pear") – Count occurrences of an item
- fruits.index("apple") – Find the index of an item
Tuples are memory efficient and offer some protection against accidental changes. Use them when you have a collection that won‘t need to be modified.
Dictionaries
Dictionaries (or dicts) store key-value pairs. They are:
- Ordered (as of Python 3.7)
- Changeable – You can change items after creation
- Does not allow duplicates – Each key must be unique
Creating a dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Accessing values:
car["brand"] # "Ford"
car.get("year") # 1964
Modifying a dictionary:
car["year"] = 2020
car.update({"color": "red"})
Some useful dictionary methods:
- len(car) – Get the number of key-value pairs
- car.keys() – Get all the keys
- car.values() – Get all the values
- car.items() – Get all key-value pairs
- car.pop("model") – Remove a key-value pair
- car.clear() – Empty the dictionary
Dictionaries provide a logical way of associating related pieces of information. They are ideal for storing structured data and offer very fast lookups by key.
Sets
Sets store multiple items in a single variable. Sets are:
- Unordered – Items are unindexed
- Unchangeable – Cannot change items, but you can add/remove
- Do not allow duplicates – Each item must be unique
Creating a set:
fruits = {"apple", "banana", "orange"}
Adding and removing items:
fruits.add("pear")
fruits.remove("banana")
fruits.discard("kiwi") # doesn‘t raise error if not found
Useful set operations:
- len(fruits) – Get number of items
- fruits.pop() – Remove a random item
- fruits.clear() – Empty the set
- "apple" in fruits – Check if item exists
Sets also support mathematical set operations like:
set1.union(set2) # combine, removing dupes
set1.intersection(set2) # shared items
set1.difference(set2) # items in set1 but not set2
Sets are an efficient way to store unique values and quickly check for membership. However, since they are unordered, they are not indexed and have limited functionality compared to lists or dictionaries.
Choosing the right data structure
With multiple built-in options, it‘s important to choose the right data structure for your specific needs. Here are some general guidelines:
- Use lists if you have an ordered collection of items
- Use tuples if you have an ordered, immutable collection of items
- Use dictionaries if you have key-value pairs and want fast lookups by key
- Use sets if you need to store unique items and check membership
Here are some examples to illustrate:
Example 1: Storing student grades
grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 88
}
Example 2: Storing items in a shopping cart
cart = ["bread", "milk", "eggs", "cheese"]
Example 3: Storing weekdays
weekdays = ("Mon", "Tues", "Wed", "Thurs", "Fri")
Example 4: Storing user IDs
user_ids = {4422, 1133, 9090, 4422} # dupes removed!
Beyond the basics
While lists, tuples, dictionaries and sets are the main built-in data structures, there are a few others worth mentioning:
-
Strings: Used to store text. Immutable ordered sequence of Unicode characters. Offers many manipulation methods.
-
Ranges: Used for looping a specific number of times in for loops. Immutable sequence type.
-
Collections module: Provides specialized container datatypes like OrderedDict, defaultdict, Counter, deque, namedtuple.
As you progress in your Python journey, you‘ll also encounter user-defined data structures like stacks, queues, trees, and linked lists. Mastering the built-in structures first provides a strong foundation for understanding these more advanced concepts.
Conclusion
We‘ve covered a lot in this guide to Python‘s built-in data structures. To recap:
- Lists are mutable ordered sequences of items
- Tuples are immutable ordered sequences of items
- Dictionaries are key-value pairs, unordered in Python 3.6 and ordered in Python 3.7+
- Sets are unordered collections of unique items
Choosing the appropriate data structure—and knowing when to use a list versus a tuple, or a dict versus a set—is an important skill in Python programming. I hope this guide has provided you with a solid understanding of the strengths and limitations of each built-in data type.
As you put your new knowledge into practice, refer back to this guide anytime you need a refresher. Remember, the best way to solidify these concepts is by writing your own code. Challenge yourself with practice problems and experiment with different data structures to gain hands-on experience.
With a strong grasp of these fundamental building blocks, you‘ll be well on your way to becoming an adept Pythonista. Happy coding!