List Method in Python

Most Important List Methods for Interviews


MethodPurpose
append(x)Add one item at the end
extend(iterable)Add multiple items
insert(i, x)Insert at a specific position
remove(x)Remove first matching value
pop([i])Remove and return an item (last by default)
clear()Remove all items
index(x)Find the position of an item
count(x)Count occurrences of an item
sort()Sort the list
reverse()Reverse the list in place
copy()Create a shallow copy
len(list)Get the number of elements
inCheck if an element exists

 


In Python slicing, a double colon (::) is used to specify the step (or stride).


  • start → Starting index (inclusive)
  • end → Ending index (exclusive)
  • step → How many positions to move each time   

  • list[start : end : step] 

    numbers = [10, 20, 30, 40, 50, 60, 70]


    Index:    0   1   2   3   4   5   6

    Value:   10  20  30  40  50  60  70


    1. [:] → Copy the entire list


    print(numbers[:]) //[10, 20, 30, 40, 50, 60, 70]


    2. ::2 → Every 2nd element


    print(numbers[::2]) //[10, 30, 50, 70]


    same as -3. ::3 → Every 3rd element


    4. [::-1] → Reverse the list


    print(numbers[::-1])

    [70, 60, 50, 40, 30, 20, 10]


    -1 means move backward one step.


    5. [::-2] → Reverse, skipping every other element


    print(numbers[::-2])


    [70, 50, 30, 10]

    Indexes:
    6 → 4 → 2 → 0


    6. Start, End, and Step Together

    print(numbers[1:6:2]) //[20, 40, 60]


    Explanation:

    • Start = index 1
    • End = index 6 (not included)
    • Step = 2

    Indexes:
    1 → 3 → 5


    7. Negative Step


    print(numbers[5:1:-1]) //[60, 50, 40, 30]

    Indexes:
    5 → 4 → 3 → 2

    Stop before index 1.

    Comments

    Popular posts from this blog

    Two Sum II - Input Array Is Sorted

    Comparable Vs. Comparator in Java

    First negative in every window of size k