Contents
Python Data Structures Explained
Data structures decide how you store and organize your values. This topic covers lists, tuples, dictionaries, and sets, and helps you pick the right one for each task.
a. Lists and Tuples
A list is an ordered collection of items inside square brackets. You can change a list by adding, removing, or updating items. Lists are the most common way to hold a group of values.
prices = [100, 250, 175]
prices.append(300)
print(prices[0])A tuple looks similar but uses round brackets, and it cannot be changed after creation. This makes tuples good for fixed data, like a pair of latitude and longitude values.
Both support indexing, which means you can pick an item by its position. Python starts counting from 0, so the first item is at index 0. You can also use slicing to pick a range of items.
b. Dictionaries
A dictionary stores data as key and value pairs. Each key is a unique label that points to a value. This makes it easy to look up information by name instead of position.
student = {"name": "Ravi", "age": 21, "course": "Python"}
print(student["name"])Dictionaries are everywhere in data work. JSON data from websites and APIs looks just like a Python dictionary. Pandas can also build a table directly from a dictionary.
You can add new keys, update values, and loop through all the items. Use the .get() method to read a key safely without causing an error if it is missing.
c. Sets
A set is a collection of unique items. If you add the same value twice, Python keeps only one copy. Sets are written inside curly brackets.
cities = {"Chennai", "Delhi", "Chennai", "Mumbai"}
print(cities)Sets are very handy for removing duplicates from a list. You can convert a list to a set and get only the unique values. This is a quick way to count how many different items you have.
Sets also support math-style operations like union and intersection. For example, you can find which customers appear in both of two lists. Keep in mind that sets are unordered, so you cannot use an index with them.
d. Choosing the Right Data Structure
Each data structure has a best use. Use a list when order matters and you may need to change items. Use a tuple when the values should stay fixed.
Use a dictionary when you want to find values by a label. Use a set when you only care about unique items or need fast checks for whether something exists.
A simple tip is to ask what you need to do with the data. If you need to look things up by name, choose a dictionary. If you need to remove repeats, choose a set. Making this choice early keeps your code clean and fast.
Data Analysis with Python Handbook
Wesline Rinisha








