Python Data Structures
Data science involves storing and processing different kinds of information, including numerical observations, customer profiles, categorical values, and transaction identifiers.
Python provides built-in data structures designed to organise these values efficiently.
Lists, tuples, dictionaries, and sets are fundamental Python data structures used to store collections of objects, access information, and perform common data-processing operations.
Each structure differs in its ordering behaviour, mutability, access methods, and handling of duplicate values.
Understanding these differences helps programmers choose suitable representations before progressing to NumPy arrays and Pandas DataFrames.
What Are Lists in Python?
A list is an ordered, mutable collection of objects.
Lists are created using square brackets and can contain elements of different data types.
For example:
sales = [1500, 2200, 1800, 3000]print(sales)Output:
[1500, 2200, 1800, 3000]Lists support indexing, slicing, insertion, modification, and deletion.
Accessing List Elements
Python uses zero-based indexing.
sales = [1500, 2200, 1800, 3000]print(sales[0])print(sales[-1])Output:
1500
3000Index 0 retrieves the first element, while index -1 retrieves the last element.
Updating a List
Lists are mutable, meaning their contents can be modified after creation.
sales = [1500, 2200, 1800]sales[1] = 2500print(sales)Output:
[1500, 2500, 1800]Common List Methods
| Method | Purpose |
|---|---|
append() |
Adds one element at the end |
extend() |
Adds elements from an iterable |
insert() |
Inserts an element at a specified position |
remove() |
Removes the first matching value |
pop() |
Removes and returns an element |
sort() |
Sorts the list in place |
count() |
Counts occurrences of a value |
For example:
sales = [1500, 2200, 1800]sales.append(3000)sales.sort()print(sales)Output:
[1500, 1800, 2200, 3000]How Are Lists Used in Data Science?
Lists are suitable for small collections, temporary data storage, and intermediate processing.
For example, a list can store daily sales before the values are converted into a NumPy array.
However, Python lists do not support NumPy-style element-wise numerical arithmetic directly.
An expression such as sales * 2 repeats the list rather than multiplying every element by two.
This distinction explains why NumPy arrays are preferred for many numerical calculations.
What Are Tuples in Python?
A tuple is an ordered, immutable collection.
Tuples are commonly created using parentheses.
coordinates = (28.6139, 77.2090)print(coordinates)Output:
(28.6139, 77.209)Tuple elements can be accessed using indexing.
print(coordinates[0])print(coordinates[1])Output:
28.6139
77.209Unlike lists, tuples do not allow their elements to be reassigned after creation.
For example, attempting to execute coordinates[0] = 30.0 raises a TypeError.
A tuple can still contain mutable objects, such as lists, whose internal contents may change.
Tuple Unpacking
Tuple unpacking assigns collection elements to separate variables.
latitude, longitude = (28.6139, 77.2090)print(latitude)print(longitude)Output:
28.6139
77.209Tuple unpacking is useful when functions return multiple values.
For example, a statistical function may return the mean and standard deviation of a dataset.
What Are Dictionaries in Python?
A dictionary stores data as key-value pairs.
Each key uniquely identifies an associated value.
Dictionaries are created using curly braces.
customer = { "name": "Aarav", "age": 25, "city": "Delhi", "total_spending": 12000}print(customer)Dictionaries are commonly used to represent structured information.
For example, a customer record can contain demographic attributes, purchase histories, and account information.
Accessing Dictionary Values
Values are accessed using their keys.
print(customer["name"])print(customer["total_spending"])Output:
Aarav
12000The get() method provides another way to access values.
print(customer.get("membership_status"))Output:
NoneUnlike direct key indexing, get() returns a default value of None when the specified key does not exist.
Updating Dictionary Values
Dictionaries are mutable.
customer["total_spending"] = 15000customer["membership_status"] = "Active"print(customer)The existing spending value is updated, and a new key-value pair is added.
Common Dictionary Methods
| Method | Purpose |
|---|---|
keys() |
Returns a view of dictionary keys |
values() |
Returns a view of dictionary values |
items() |
Returns key-value pairs |
get() |
Retrieves a value with an optional default |
update() |
Adds or updates key-value pairs |
pop() |
Removes a specified key and returns its value |
How Are Dictionaries Used in Data Science?
Dictionaries are particularly useful when working with JSON data and API responses.
Consider the following record:
transaction = { "transaction_id": 1001, "customer_id": "C101", "amount": 2500, "status": "Success"}A collection of dictionaries can represent multiple structured records.
transactions = [ {"customer": "Aarav", "amount": 2500}, {"customer": "Priya", "amount": 4200}, {"customer": "Rohan", "amount": 1800}]This structure can be converted into a Pandas DataFrame for tabular analysis.
What Are Sets in Python?
A set is an unordered collection of unique, hashable elements.
Sets are created using curly braces or the set() constructor.
customer_ids = {101, 102, 103, 101}print(len(customer_ids))Output:
3Although the value 101 appears twice in the original expression, the set retains only one occurrence.
Sets are useful for identifying unique identifiers and comparing collections.
Set Operations
Python supports several mathematical set operations.
Consider two groups of customer IDs.
group_a = {101, 102, 103}group_b = {102, 103, 104}Union: Combines unique elements from both sets.
print(group_a | group_b)The resulting set contains 101, 102, 103, and 104.
Intersection: Identifies elements present in both sets.
print(group_a & group_b)The resulting set contains 102 and 103.
Difference: Identifies elements present in the first set but absent from the second.
print(group_a - group_b)The resulting set contains 101.
Set operations are useful for comparing customer groups, identifying overlapping categories, and validating identifiers across datasets.
Python Data Structures Comparison
| Feature | List | Tuple | Dictionary | Set |
|---|---|---|---|---|
| Ordered | Yes | Yes | Preserves insertion order | No positional order |
| Mutable | Yes | No | Yes | Yes |
| Duplicate Elements | Allowed | Allowed | Keys must be unique | Not allowed |
| Access Method | Index | Index | Key | Membership |
| Syntax | [] |
() |
{key: value} |
{value} |
| Typical Use | Numerical collections | Fixed records | Structured information | Unique values |
How Do You Choose the Right Data Structure?
The correct structure depends on the intended operation.
A list is appropriate when storing an ordered collection whose contents may change.
A tuple is suitable for a fixed sequence or for returning multiple values from a function.
A dictionary is useful when individual fields require meaningful keys.
A set is appropriate when uniqueness and membership testing are important.
Practical Example of Combining Data Structures
Consider an e-commerce dataset containing customer purchase records.
orders = [ {"customer_id": 101, "amount": 2500}, {"customer_id": 102, "amount": 4200}, {"customer_id": 101, "amount": 1800}]unique_customers = set()for order in orders: unique_customers.add(order["customer_id"])print(len(unique_customers))Output:
2This example combines three programming concepts:
- A list stores multiple transaction records.
- Dictionaries represent individual records.
- A set stores unique customer IDs.
Such operations are common in data validation and preprocessing.
How Do Python Data Structures Connect to NumPy and Pandas?
Lists and dictionaries provide convenient representations for small datasets.
However, NumPy arrays and Pandas DataFrames are generally more suitable for many large-scale numerical and tabular operations.
NumPy arrays support efficient element-wise arithmetic and multidimensional numerical operations.
Pandas DataFrames represent datasets using labelled rows and columns, supporting filtering, aggregation, and data transformation.
Understanding built-in Python collections therefore provides the foundation for learning specialised data science libraries.
Common Mistakes Beginners Should Avoid
- Confusing lists and tuples: Lists allow element reassignment, whereas tuples do not.
- Using duplicate dictionary keys: Assigning the same key again replaces its previous value.
- Assuming sets preserve insertion order: Sets do not provide positional indexing or an insertion-order guarantee.
- Accessing unavailable dictionary keys: Direct indexing raises a
KeyError. - Using lists for large numerical calculations: NumPy arrays may offer more efficient numerical operations.
Data Science Tutorial for Beginners
Vaishali Ardhana








