List Data Structure in Python

What is a List?

So far you've stored one value in one variable:


    student1 = "Rahul"
    student2 = "Priya"
    student3 = "Gagan"

What if you have 100 students? You can't create 100 variables. That's where Lists come in.

A list stores multiple values in a single variable:


    students = ["Rahul", "Priya", "Gagan"]

Done. 3 students in one variable. Scale this to 100 or 1000 — same concept.


Creating a List


    # List of strings
    fruits = ["apple", "banana", "mango", "orange"]

    # List of numbers
    marks = [85, 90, 78, 92, 88]

    # List of mixed types (allowed in Python)
    mixed = ["Gagan", 22, 5.11, True]

    # Empty list
    empty = []

    print(fruits)
    print(marks)

Output:

['apple', 'banana', 'mango', 'orange']
[85, 90, 78, 92, 88]

Indexing — Accessing Items

Every item in a list has a position called index. Indexing starts from 0 in Python:


    fruits = ["apple", "banana", "mango", "orange"]
    #           0         1         2        3

    print(fruits[0])    # apple
    print(fruits[1])    # banana
    print(fruits[2])    # mango
    print(fruits[3])    # orange


Negative Indexing

Python also allows counting from the end using negative numbers:


    fruits = ["apple", "banana", "mango", "orange"]

    print(fruits[-1])    # orange  (last item)
    print(fruits[-2])    # mango   (second last)
    print(fruits[-4])    # apple   (fourth from end)

Very useful when you want the last item and don't know the length of the list.


Slicing — Getting a Portion of a List

You can extract a section of a list using [start:end]:


    fruits = ["apple", "banana", "mango", "orange", "grapes"]

    print(fruits[1:3])     # ['banana', 'mango']  (index 1 and 2, not 3)
    print(fruits[0:3])     # ['apple', 'banana', 'mango']
    print(fruits[2:])      # ['mango', 'orange', 'grapes']  (from index 2 to end)
    print(fruits[:3])      # ['apple', 'banana', 'mango']   (from start to index 2)
    print(fruits[:])       # entire list

Same rule as range — end index is not included.


Modifying Items

Lists are mutable — you can change their values after creation:


    fruits = ["apple", "banana", "mango"]
    print(fruits)          # ['apple', 'banana', 'mango']

    fruits[1] = "grapes"   # replace banana with grapes
    print(fruits)          # ['apple', 'grapes', 'mango']


List Methods — Built-in Operations

Python gives you many built-in methods to work with lists:

Adding Items


    fruits = ["apple", "banana"]

    fruits.append("mango")         # add to the END
    print(fruits)                  # ['apple', 'banana', 'mango']

    fruits.insert(1, "orange")     # add at specific index
    print(fruits)                  # ['apple', 'orange', 'banana', 'mango']


Removing Items


    fruits = ["apple", "banana", "mango", "orange"]

    fruits.remove("banana")        # remove by value
    print(fruits)                  # ['apple', 'mango', 'orange']

    fruits.pop()                   # remove last item
    print(fruits)                  # ['apple', 'mango']

    fruits.pop(0)                  # remove by index
    print(fruits)                  # ['mango']


Other Useful Methods


    numbers = [3, 1, 4, 1, 5, 9, 2, 6]

    print(len(numbers))            # 8 — total items in list
    print(numbers.count(1))        # 2 — how many times 1 appears
    print(numbers.index(5))        # 4 — index of value 5

    numbers.sort()                 # sort in ascending order
    print(numbers)                 # [1, 1, 2, 3, 4, 5, 6, 9]

    numbers.reverse()              # reverse the list
    print(numbers)                 # [9, 6, 5, 4, 3, 2, 1, 1]

    numbers.sort(reverse=True)     # sort in descending order
    print(numbers)                 # [9, 6, 5, 4, 3, 2, 1, 1]


Checking if Item Exists


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

    print("banana" in fruits)      # True
    print("grapes" in fruits)      # False

    if "mango" in fruits:
        print("Yes we have mango!")


Looping Through a List

This is where lists really shine — combine with for loops:


    fruits = ["apple", "banana", "mango", "orange"]

    for fruit in fruits:
        print(fruit)

Output:

apple
banana
mango
orange

With index using enumerate():


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

    for index, fruit in enumerate(fruits):
        print(f"{index + 1}. {fruit}")

Output:

1. apple
2. banana
3. mango

enumerate() gives you both the index and the value at the same time. Very useful.


List with Functions — Practical Example


    def get_total(marks):
        total = 0
        for mark in marks:
            total += mark
        return total

    def get_average(marks):
        return get_total(marks) / len(marks)

    def get_highest(marks):
        return max(marks)

    def get_lowest(marks):
        return min(marks)


    marks = [85, 90, 78, 92, 88, 76]

    print(f"Marks: {marks}")
    print(f"Total: {get_total(marks)}")
    print(f"Average: {get_average(marks):.2f}")
    print(f"Highest: {get_highest(marks)}")
    print(f"Lowest: {get_lowest(marks)}")

Output:

Marks: [85, 90, 78, 92, 88, 76]
Total: 509
Average: 84.83
Highest: 92
Lowest: 76

List of Lists — 2D List

A list can contain other lists. This is like a table with rows and columns:


    students = [
        ["Rahul", 85, "A"],
        ["Priya", 92, "A+"],
        ["Gagan", 78, "B"]
    ]

    # Accessing
    print(students[0])          # ['Rahul', 85, 'A']
    print(students[0][0])       # Rahul  (row 0, column 0)
    print(students[1][1])       # 92     (row 1, column 1)

    # Looping
    for student in students:
        print(f"Name: {student[0]}, Marks: {student[1]}, Grade: {student[2]}")

Output:

Name: Rahul, Marks: 85, Grade: A
Name: Priya, Marks: 92, Grade: A+
Name: Gagan, Marks: 78, Grade: B

Common Mistake — Copying a List

This is a classic beginner trap:


    list1 = [1, 2, 3]
    list2 = list1          # this is NOT a copy — both point to same list

    list2.append(4)
    print(list1)           # [1, 2, 3, 4] — list1 also changed!
    print(list2)           # [1, 2, 3, 4]

To make a proper independent copy:


    list1 = [1, 2, 3]
    list2 = list1.copy()   # proper copy

    list2.append(4)
    print(list1)           # [1, 2, 3]   — unchanged
    print(list2)           # [1, 2, 3, 4]


Real World Example — Shopping Cart


    cart = []

    def show_cart():
        if len(cart) == 0:
            print("Cart is empty")
        else:
            print("\n=== Your Cart ===")
            for index, item in enumerate(cart):
                print(f"{index + 1}. {item}")
            print(f"Total items: {len(cart)}")

    def add_item():
        item = input("Enter item name: ")
        cart.append(item)
        print(f"{item} added to cart!")

    def remove_item():
        show_cart()
        if len(cart) > 0:
            item = input("Enter item to remove: ")
            if item in cart:
                cart.remove(item)
                print(f"{item} removed!")
            else:
                print("Item not found in cart")

    while True:
        print("\n=== Shopping Cart ===")
        print("1. Add item")
        print("2. Remove item")
        print("3. View cart")
        print("4. Exit")

        choice = input("Enter choice: ")

        if choice == "1":
            add_item()
        elif choice == "2":
            remove_item()
        elif choice == "3":
            show_cart()
        elif choice == "4":
            print("Thank you for shopping!")
            break
        else:
            print("Invalid choice")

This is a real mini-application — using everything you've learned so far together.


Quick Reference — All List Methods

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

fruits.append("orange")       # add to end
fruits.insert(1, "grapes")    # add at index
fruits.remove("banana")       # remove by value
fruits.pop()                  # remove last
fruits.pop(0)                 # remove by index
fruits.sort()                 # sort ascending
fruits.reverse()              # reverse
fruits.clear()                # remove all items
fruits.copy()                 # make a copy
len(fruits)                   # count items
"apple" in fruits             # check existence
fruits.index("mango")         # find index of value
fruits.count("apple")         # count occurrences

Exercise 🏋️

Build a Number Analyzer program:

  1. Ask user to enter 5 numbers one by one and store them in a list
  2. Then display:
    • All numbers
    • Sum of all numbers
    • Average
    • Highest number
    • Lowest number
    • All even numbers from the list
    • All odd numbers from the list
    • List sorted in ascending order

Expected output:

Enter number 1: 15
Enter number 2: 8
Enter number 3: 23
Enter number 4: 4
Enter number 5: 16

=== Analysis ===
Numbers: [15, 8, 23, 4, 16]
Sum: 66
Average: 13.20
Highest: 23
Lowest: 4
Even numbers: [8, 4, 16]
Odd numbers: [15, 23]
Sorted: [4, 8, 15, 16, 23]

Hint: Use a for loop to collect numbers, and another for loop to separate even and odd numbers into two separate lists.


No comments:

Post a Comment

Phase 3 — Components Deep Dive

Chapter 1 — What We Are Going to Learn and Why In Phase 2 you learned what a component is and how to create one. You know that a component h...