Menu
Courses / python basic / Data Structures

Data Structures

02 / 10 Part of python basic




 

    📚 Topic 07 · Collections
 

 


    Data Structures
 


 


    Master Python's built-in collections — lists, dictionaries, tuples, and sets — and learn when to use each one.
 


 

    ⏱ ~50 min
    🟡 Intermediate
    🗂️ Core
 


 
 

   

     
     

Lists


   

   

Ordered, mutable sequences. The most versatile collection in Python.


   

     

        lists.py
     

     
fruits = ["apple", "banana", "cherry"]

fruits.append("date")       # add to end
fruits.insert(1, "avocado") # insert at index
fruits.remove("banana")    # remove by value
popped = fruits.pop()        # remove and return last

print(fruits[0])    # apple
print(fruits[-1])   # last element
print(fruits[1:3])  # slice

# List comprehension
squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

   

 


 
 

   

     
     

Dictionaries


   

   

Key-value stores with O(1) lookup. Keys must be unique and immutable.


   

     

        dicts.py
     

     
person = {"name": "Alice", "age": 30}

print(person["name"])                 # Alice
print(person.get("height", "N/A"))   # N/A (safe)

person["email"] = "alice@mail.com"     # add/update
del person["age"]                      # delete key

for key, value in person.items():
    print(f"{key} → {value}")

   

 


 
 

   

     
     

Tuples


   

   

Immutable ordered sequences. Use when data must not change — coordinates, RGB values, database records.


   

     

        tuples.py
     

     
point = (10, 20)
x, y = point            # unpacking
print(x, y)             # 10 20

# Tuples can be used as dict keys (lists cannot)
grid = {(0, 0): "origin"}

   

 


 
 

   

     
     

Sets


   

   

Unordered collections of unique items. Perfect for membership tests and deduplication.


   

     

        sets.py
     

     
tags = {"python", "coding", "python"}
print(tags)          # {'coding', 'python'} — no duplicates

a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)         # union: {1,2,3,4}
print(a & b)         # intersection: {2,3}
print(a - b)         # difference: {1}

print("python" in tags)  # True — O(1) lookup

   

   

      📌 Which collection to choose?
     

Need order + duplicates → list. Need key-value pairs → dict. Need immutable sequence → tuple. Need uniqueness + fast lookup → set.