Python Tutorial

Python List Methods

Below is a table summarizing common Python list methods, including their descriptions and examples of how to use them.

Method Description Example
append(x) Adds an item x to the end of the list. my_list.append(10)
extend(iterable) Extends the list by appending all elements from the given iterable. my_list.extend([1, 2, 3])
insert(i, x) Inserts an item x at a given index i. my_list.insert(2, 'apple')
remove(x) Removes the first occurrence of the item x from the list. my_list.remove('apple')
pop([i]) Removes and returns the item at the given index i. If i is not provided, it removes and returns the last item. item = my_list.pop(2)
clear() Removes all items from the list, leaving it empty. my_list.clear()
index(x[, start[, end]]) Returns the index of the first occurrence of the item x. The search can be limited to a subsequence by specifying the start and end indices. idx = my_list.index('apple')
count(x) Returns the number of times the item x appears in the list. count = my_list.count(10)
sort(key=None, reverse=False) Sorts the list in ascending order by default. The sorting order can be customized using the key function and reverse parameter. my_list.sort() my_list.sort(reverse=True)
reverse() Reverses the order of the items in the list. my_list.reverse()
copy() Returns a shallow copy of the list. new_list = my_list.copy()

Examples

Here are some examples to demonstrate how these methods work:

  1. Append Example:

    my_list = [1, 2, 3]
    my_list.append(4)
    print(my_list)
    

    Output: [1, 2, 3, 4]

  2. Extend Example:

    my_list = [1, 2, 3]
    my_list.extend([4, 5, 6])
    print(my_list)
    

    Output: [1, 2, 3, 4, 5, 6]

  3. Insert Example:

    my_list = [1, 2, 3]
    my_list.insert(1, 'apple')
    print(my_list)
    

    Output: [1, 'apple', 2, 3]

  4. Remove Example:

    my_list = ['apple', 'banana', 'cherry']
    my_list.remove('banana')
    print(my_list)
    
    

    Output: ['apple', 'cherry']

  5. Pop Example:

    my_list = [1, 2, 3, 4]
    item = my_list.pop(2)
    print(item)  # Output: 3
    print(my_list)  # Output: [1, 2, 4]
    
  6. Clear Example:

    my_list = [1, 2, 3]
    my_list.clear()
    print(my_list)
    

    Output: []

  7. Index Example:

    my_list = ['apple', 'banana', 'cherry']
    idx = my_list.index('banana')
    print(idx)
    

    Output: 1

  8. Count Example:

    my_list = [1, 2, 2, 3, 2]
    count = my_list.count(2)
    print(count)
    

    Output: 3

  9. Sort Example:

    my_list = [3, 1, 2]
    my_list.sort()
    print(my_list)
    

    Output: [1, 2, 3]

  10. Reverse Example:

    my_list = [1, 2, 3]
    my_list.reverse()
    print(my_list)
    
    

    Output: [3, 2, 1]

  11. Copy Example:

    my_list = [1, 2, 3]
    new_list = my_list.copy()
    print(new_list)
    

    Output: [1, 2, 3]