5.10 Python in-built functions for Lists (BT101CO)

To master list manipulation, you must distinguish between Functions (which take the list as an input and usually return a new value) and Methods (which are called on the list itself and often modify it in-place).

1. Built-in List Functions

These functions are standalone and take the list as an argument. They are highly optimized for analyzing data.

  • len(list): Returns the total number of elements.
  • max(list): Returns the item with the maximum value.
  • min(list): Returns the item with the minimum value.
  • sum(list): Calculates the total sum of numerical elements.
  • sorted(list): Returns a new sorted list.
  • list(reversed(list)): Returns an iterator to access the list backward.

Example:

scores = [85, 92, 78, 90, 88]
print(len(scores))  # 5
print(max(scores))  # 92
print(sum(scores))  # 433

2. Common List Methods

Methods use the list.method() syntax. Most of these change the original list in memory (mutability).

Method Action Resulting List example
.append(x)Adds x to the end.[1, 2, 3]
.extend(L)Appends all items of list L.Concatenated list
.insert(i, x)Inserts x at index i.Shifted list
.remove(x)Deletes the first occurrence of x.Value removed
.pop(i)Removes and returns item at i.Index removed
.sort()Sorts the list **in-place**.Sorted original

3. Exam-Oriented Solved Examples

A. Removing Duplicates (The set shortcut)

nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = list(set(nums)) # Order might change
# Output: [1, 2, 3, 4, 5]

B. Finding Frequency (The count logic)

words = ["python", "Java", "Python", "C++", "PYTHON"]
target = "python"
count = 0
for w in words:
    if w.lower() == target:
        count += 1
print(f"Occurrences: {count}") # Output: 3

4. Critical Exam "Traps"

  • Trap 1: append() vs extend()

    L.append([3, 4])[1, 2, [3, 4]] (Nested list)
    L.extend([3, 4])[1, 2, 3, 4] (Flattened list)

  • Trap 2: sort() vs sorted()

    my_list.sort() returns None and modifies the list.
    new_list = sorted(my_list) returns a New List.

  • Trap 3: Assignment vs Copying

    list_b = list_a points to the same object.
    list_b = list_a[:] creates a True Copy.

5. Advanced Logic: Negative Indexing Masterclass

Negative indexing starts at -1 (the last element). It is essential for accessing data without knowing the list length.

Negative Indexing in Slicing

Example: L = [10, 20, 30, 40, 50, 60]

Slice Result Logic
L[-3:][40, 50, 60]Start at 3rd from end to the end.
L[:-2][10, 20, 30, 40]Start at beginning to 2nd from end.
L[-4:-1][30, 40, 50]Between 4th from end and last.

Exam "Trap" Questions

  • The Out-of-Bounds Trap: L[-4] on [1, 2, 3] raises an IndexError.
  • The Empty Slice Trick: L[-1:-3] results in [] because the default step is +1. Use L[-1:-3:-1] to fix it.

Practice Quiz