PYTHON LISTS

Store, modify, sort, and organize collections of items using Python's built-in ordered and mutable list data structures.

📋 What is a List in Python?

A list is an ordered and mutable (changeable) collection of items enclosed in square brackets []. Lists allow duplicate elements, mixed data types, and provide powerful methods to insert, delete, sort, and query data dynamically.

1. Basic List Declaration and Indexing
Declare a list of items and access individual elements using zero-based index positions.
Python
# Creating a list of web design languages
languages = ["HTML", "CSS", "JavaScript", "Python"]

print("First Item:", languages[0])
print("Last Item:", languages[-1])
Output: First Item: HTML Last Item: Python
Real-Time Example 1: E-Commerce Shopping Cart Manager
Manage user items added to an active shopping cart by appending new purchases and removing items.
Python
cart = ["Laptop Sleeve", "Wireless Mouse"]

# User adds a keyboard
cart.append("Mechanical Keyboard")

# User decides to remove the laptop sleeve
cart.remove("Laptop Sleeve")

print("Current Shopping Cart:", cart)
print("Total items in cart:", len(cart))
Output: Current Shopping Cart: ['Wireless Mouse', 'Mechanical Keyboard'] Total items in cart: 2
Real-Time Example 2: Student Examination Grade Evaluator
Calculate average scores, highest marks, and lowest marks from a student's grade list.
Python
exam_scores = [78, 85, 92, 64, 90]

highest_score = max(exam_scores)
lowest_score = min(exam_scores)
average_score = sum(exam_scores) / len(exam_scores)

print(f"Highest Score: {highest_score}")
print(f"Lowest Score: {lowest_score}")
print(f"Average Class Score: {average_score:.2f}")
Output: Highest Score: 92 Lowest Score: 64 Average Class Score: 81.80
Real-Time Example 3: Task Management Checklist
Insert priority tasks at specific positions using insert() and mark them complete.
Python
todo_list = ["Review Database Schema", "Deploy Server"]

# Insert an urgent task at the very beginning (index 0)
todo_list.insert(0, "Fix Critical Login Bug")

print("Updated Todo Checklist:")
for index, task in enumerate(todo_list, 1):
    print(f"{index}. {task}")
Output: Updated Todo Checklist: 1. Fix Critical Login Bug 2. Review Database Schema 3. Deploy Server
Real-Time Example 4: Inventory Sorting and Reversing
Organize product SKU codes alphabetically or reverse order using sort() and reverse().
Python
product_skus = ["SKU-902", "SKU-105", "SKU-441", "SKU-201"]

# Sort alphabetically (ascending)
product_skus.sort()
print("Sorted SKUs (Ascending):", product_skus)

# Sort in reverse alphabetical order (descending)
product_skus.sort(reverse=True)
print("Sorted SKUs (Descending):", product_skus)
Output: Sorted SKUs (Ascending): ['SKU-105', 'SKU-201', 'SKU-441', 'SKU-902'] Sorted SKUs (Descending): ['SKU-902', 'SKU-441', 'SKU-201', 'SKU-105']
Real-Time Example 5: Filtering Data with List Comprehension
Extract items meeting specific criteria (e.g., filtering out expired stock or prices below threshold).
Python
item_prices = [120, 45, 300, 85, 500, 20]

# Filter items that cost more than 100
premium_items = [price for price in item_prices if price > 100]

print("Original Prices:", item_prices)
print("Premium Items (> 100):", premium_items)
Output: Original Prices: [120, 45, 300, 85, 500, 20] Premium Items (> 100): [120, 300, 500]
Real-Time Example 6: Checking Membership Status in a Database List
Use the in operator to check whether a username or item exists in a restricted list.
Python
banned_ips = ["192.168.1.55", "10.0.0.99", "172.16.0.12"]
incoming_ip = "10.0.0.99"

if incoming_ip in banned_ips:
    print(f"Access Denied: IP {incoming_ip} is blacklisted.")
else:
    print(f"Access Granted for IP {incoming_ip}.")
Output: Access Denied: IP 10.0.0.99 is blacklisted.
Real-Time Example 7: List Slicing for Pagination
Extract subsets of a large list to display paginated records in an application report.
Python
all_transactions = ["Txn-01", "Txn-02", "Txn-03", "Txn-04", "Txn-05", "Txn-06"]

# Display page 1 (First 3 items: index 0 to 2)
page_one = all_transactions[0:3]

print("Page 1 Transactions:", page_one)
Output: Page 1 Transactions: ['Txn-01', 'Txn-02', 'Txn-03']
Real-Time Example 8: Combining and Extending Lists
Merge two separate department lists into a single company directory using extend() or the + operator.
Python
dev_team = ["Alice", "Bob"]
qa_team = ["Charlie", "Diana"]

# Merge teams
all_staff = dev_team + qa_team

print("Unified Company Staff Directory:", all_staff)
Output: Unified Company Staff Directory: ['Alice', 'Bob', 'Charlie', 'Diana']
Real-Time Example 9: Counting and Finding Item Occurrences
Count how many times a specific vote or product rating appears in a feedback list using count().
Python
customer_ratings = [5, 4, 5, 3, 5, 2, 4, 5]

five_star_count = customer_ratings.count(5)

print(f"Total 5-Star ratings received: {five_star_count}")
print(f"Total reviews submitted: {len(customer_ratings)}")
Output: Total 5-Star ratings received: 4 Total reviews submitted: 8
Real-Time Example 10: Clearing and Resetting a Session List
Wipe temporary session history or logs clean using the clear() method.
Python
active_session_logs = ["Log-A", "Log-B", "Log-C"]
print("Logs before logout:", active_session_logs)

# Clear session logs upon user logout
active_session_logs.clear()
print("Logs after user logout:", active_session_logs)
Output: Logs before logout: ['Log-A', 'Log-B', 'Log-C'] Logs after user logout: []

Summary of Python Lists

  • Ordered & Mutable: Items maintain their sequence and can be added, updated, or removed anytime.
  • Key Built-in Methods: append(), insert(), remove(), pop(), sort(), reverse(), and count().
  • Applications: Essential for handling arrays, shopping carts, task queues, logs, and datasets across web applications.