Skip to main content

Python Data Structures Explained: List, Set, Tuple, and Dictionary /Dict

 Python Data Structures Explained: List, Set, Tuple, and Dictionary

For Beginners and Intermediate Coders

Python offers versatile built-in data structures to organize and manage data efficiently. Let’s break down listssetstuples, and dictionaries—their uses, syntax, and key differences.


1. List

What is it?
list is an ordered, mutable (changeable) collection of items. It allows duplicates.

Syntax:

python
Copy
my_list = [1, "apple", 3.14, True]  

Key Features:

  • Ordered: Items maintain their insertion order.

  • Mutable: You can add, remove, or modify elements.

  • Indexed: Access items via positions (my_list[0]).

  • Flexible: Can hold mixed data types.

Common Methods:

  • append(): Add an item to the end.

  • remove(): Delete a specific item.

  • sort(): Sort elements in place.

  • Slicing: my_list[1:3] extracts items from index 1 to 2.

Use Case:
Storing a sequence of items that may need updates, like a shopping list or log entries.


2. Set

What is it?
set is an unordered, mutable collection of unique elements.

Syntax:

python
Copy
my_set = {1, 2, 3, "apple"}  
# Or: my_set = set([1, 2, 2, 3]) → {1, 2, 3} (duplicates removed)  

Key Features:

  • Unordered: No index-based access.

  • Unique Elements: Automatically removes duplicates.

  • Mutable: Add/remove items, but elements must be hashable (immutable).

  • Fast Membership Tests: Optimized for checking if an item exists ("apple" in my_set).

Common Methods:

  • add(): Insert a new item.

  • union()intersection(): Combine or compare sets.

  • discard(): Remove an item.

Use Case:
Removing duplicates from a list or checking for membership (e.g., tracking unique users).


3. Tuple

What is it?
tuple is an ordered, immutable (unchangeable) collection of items.

Syntax:

python
Copy
my_tuple = (1, "apple", 3.14)  
# Single-element tuple: (5,) (comma required!)  

Key Features:

  • Immutable: Once created, you can’t add, remove, or change elements.

  • Ordered: Items are accessed via indexes (my_tuple[0]).

  • Faster than Lists: Lightweight for fixed data.

Common Methods:

  • count(): Count occurrences of a value.

  • index(): Find the position of a value.

Use Case:
Storing unchangeable data (e.g., days of the week, coordinates) or using as keys in dictionaries.


4. Dictionary (Dict)

What is it?
dictionary stores data as key-value pairs. Keys are unique and immutable (strings, numbers, tuples).

Syntax:

python
Copy
my_dict = {"name": "Alice", "age": 30, "city": "Paris"}  

Key Features:

  • Unordered (Python 3.7+ preserves insertion order, but don’t rely on it).

  • Mutable: Add, modify, or delete key-value pairs.

  • Fast Lookups: Retrieve values instantly using keys (my_dict["name"]).

Common Methods:

  • keys(): Get all keys.

  • values(): Get all values.

  • get(): Safely retrieve a value (avoids KeyError).

  • update(): Add multiple key-value pairs.

Use Case:
Storing structured data (e.g., user profiles, configurations) or counting occurrences (e.g., word frequency).


Comparison Table

FeatureListSetTupleDictionary
OrderOrderedUnorderedOrderedUnordered (usually)
MutabilityMutableMutableImmutableMutable (keys fixed)
DuplicatesAllowedNot allowedAllowedKeys are unique
Syntax[ ]{ } or set()( ){key: value}
Use CaseDynamic dataUnique itemsFixed dataKey-value mappings

When to Use Which?

  • List: Need an ordered collection that changes frequently? Use a list.

  • Set: Working with unique items or fast membership checks? Use a set.

  • Tuple: Want to ensure data integrity (e.g., constants)? Use a tuple.

  • Dict: Need to map keys to values (e.g., JSON-like data)? Use a dictionary.


Pro Tip:

  • Use tuples as dictionary keys (since they’re immutable).

  • Sets are great for mathematical operations (e.g., union, intersection).

  • List comprehensions and dict comprehensions make code concise!

Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...