Data Structures in Python – Complete Notes

🧠 What are Data Structures?

Data structures are ways to store and organize data so we can access and modify it efficiently.

🧱 Types of Built-in Data Structures in Python

Python has 4 main built-in data structures:

TypeOrderedMutableAllows DuplicatesSyntax
List✅ Yes✅ Yes✅ Yes[]
Tuple✅ Yes❌ No✅ Yes()
Set❌ No✅ Yes❌ No (unique){}
Dictionary✅ Yes✅ Yes❌ No (unique keys){key: value}

1️⃣ Lists – Ordered and Mutable

Used to store multiple items in a single variable.

🔹 Syntax:

my_list = [10, 20, 30, "Python", True]

🔹 Operations

my_list[1]          # Access
my_list.append(40)  # Add at end
my_list.remove(20)  # Remove item
my_list[0] = 100    # Update item

2️⃣ Tuples – Ordered and Immutable

Like lists, but cannot be changed (read-only).

🔹 Syntax:

my_tuple = (10, 20, 30, "Python")

🔹 Operations

my_tuple[1]        # Access
len(my_tuple)      # Length
# Cannot add or remove elements

📌 Use when data should not be changed, like dates or constants.


3️⃣ Sets – Unordered, No Duplicates

Used to store unique values.

🔹 Syntax:

my_set = {1, 2, 3, 4, 4, 2}
print(my_set)  # Output: {1, 2, 3, 4}

🔹 Operations

my_set.add(5)        # Add item
my_set.remove(3)     # Remove item

✅ Good for membership tests and removing duplicates.


4️⃣ Dictionaries – Key-Value Pairs


Used to store data in pairs (like a real-life dictionary).

🔹 Syntax:

my_dict = {"name": "John", "age": 25, "is_student": True}

🔹 Operations

my_dict["name"]             # Access value
my_dict["age"] = 26         # Update value
my_dict["city"] = "Chennai" # Add new pair
del my_dict["is_student"]   # Delete key

🔁 Looping Through Data Structures

🔹 List/Tuple:

for item in my_list:
    print(item)

🔹 Set:

for item in my_set:
    print(item)

🔹 Dictionary:

for key, value in my_dict.items():
    print(key, value)


profile={"name":"kumar","age":20}
for key,value in profile.items():
    print(key,":",value)

Output:

name : kumar
age : 20

🧪 Example Practice:


students = ["Arun", "Beena", "Charles"]
print(students)
marks = (85, 90, 78)
print(marks)
unique_subjects = {"Math", "Science", "Math"}  
print(unique_subjects)
profile = {"name": "Kumar", "age": 20}
print(profile)

📌 Summary for Beginners:

Data TypeUse for…
ListStore changing sequences
TupleStore fixed sequences
SetStore unique items
DictionaryStore labeled data (key-value)

real-life use cases with examples

✅ 1. List – When Order & Change Matters

📌 Real-Life Use Case:

  • Shopping List – You add items, remove items, or change quantities.

🧪 Python Example:

shopping_list = ["milk", "eggs", "bread"]
shopping_list.append("butter")      # Add item
shopping_list.remove("milk")        # Remove item
shopping_list[0] = "cheese" 
# Replace "eggs" with "cheese"
print(shopping_list)  
# Output: ['cheese', 'bread', 'butter']

✅ Use When:

  • You need ordered items.
  • Items can change (mutable).
  • Duplicates are okay.

✅ 2. Tuple – When Data Shouldn’t Change

📌 Real-Life Use Case:

  • Date of Birth, GPS coordinates, or Configuration values – These don’t change.
date_of_birth = (1995, 12, 15)  # year, month, day
coordinates = (13.0827, 80.2707)  # Chennai GPS

print("Born in:", date_of_birth[0])

✅ Use When:

  • You want a fixed collection of values.
  • Memory efficiency is important.
  • Used as dictionary keys (immutable).

✅ 3. Set – When You Need Only Unique Items

📌 Real-Life Use Case:

  • Attendees List – To ensure no one is counted twice.
  • Available tags or unique student IDs.
attendees = {"Alice", "Bob", "Alice", "David"}
print(attendees)  # Output: {'Alice', 'Bob', 'David'}

attendees.add("Eve")     # Add new person
attendees.remove("Bob")  # Remove person

print(attendees)

✅ Use When:

  • Order doesn’t matter.
  • No duplicates allowed.
  • You want fast membership test (in operator).

✅ 4. Dictionary – Store Data with Labels

📌 Real-Life Use Case:

  • Student Profile, Bank Account Details, Product Catalog
student = {
    "name": "Karthik",
    "age": 21,
    "marks": 88,
    "college": "ABC University"
}

# Accessing values
print(student["name"])   # Karthik
student["marks"] = 92    # Update marks
student["city"] = "Chennai"  # Add new key
print(student)

✅ Use When:

  • You need to label values (name, age, etc.).
  • Quick lookup based on key.
  • You want structured data.

💡 Quick Analogy for Remembering:

Real LifePython Data Structure
Shopping listList
Birth certificateTuple
Guest register bookSet
Student ID cardDictionary

🔄 Mixed Example (All in One):

students = [
    {"name": "Arun", "age": 17, "subjects": {"Math", "Science"}},
    {"name": "Beena", "age": 18, "subjects": {"Math", "English"}},
]

for student in students:
    print(f"{student['name']} is {student['age']} years old and studies {student['subjects']}")

This uses:

  • List of students
  • Dictionaries to store each student’s details
  • Sets to store unique subjects

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *