Python List functions


Here’s a comprehensive list of the built-in list methods in Python, along with a brief description of each:

List Methods in Python

  1. list.append(x)

    • Adds an item x to the end of the list.
  2. list.extend(iterable)

    • Extends the list by appending elements from an iterable (e.g., another list).
  3. list.insert(i, x)

    • Inserts an item x at a given position i in the list.
  4. list.remove(x)

    • Removes the first occurrence of an item x from the list. Raises a ValueError if the item is not found.
  5. list.pop([i])

    • Removes and returns the item at the given position i. If no index is specified, pop() removes and returns the last item in the list.
  6. list.clear()

    • Removes all items from the list.
  7. list.index(x[, start[, end]])

    • Returns the index of the first occurrence of an item x in the list. Raises a ValueError if the item is not found. You can also specify a start and end index for searching.
  8. list.count(x)

    • Returns the number of occurrences of an item x in the list.
  9. list.sort(key=None, reverse=False)

    • Sorts the items of the list in place (the arguments can be used for custom sorting).
  10. list.reverse()

    • Reverses the elements of the list in place.
  11. list.copy()

    • Returns a shallow copy of the list.

Example Usage of List Methods

Here’s a brief example demonstrating some of these methods:

# Create a list my_list = [1, 2, 3, 4] # Append an item my_list.append(5) # my_list is now [1, 2, 3, 4, 5] # Extend the list my_list.extend([6, 7]) # my_list is now [1, 2, 3, 4, 5, 6, 7] # Insert an item my_list.insert(0, 0) # my_list is now [0, 1, 2, 3, 4, 5, 6, 7] # Remove an item my_list.remove(4) # my_list is now [0, 1, 2, 3, 5, 6, 7] # Pop an item last_item = my_list.pop() # Removes and returns 7, my_list is now [0, 1, 2, 3, 5, 6] # Clear the list my_list.clear() # my_list is now [] # Count occurrences my_list = [1, 2, 2, 3] count_of_twos = my_list.count(2) # Returns 2 # Sorting my_list.sort() # Sorts the list in place # Reversing my_list.reverse() # Reverses the list in place # Copying new_list = my_list.copy() # Creates a shallow copy of my_list

Summary

These methods provide a rich set of functionalities for manipulating lists in Python, making it easy to add, remove, and modify elements within a list.