📜

Python List Methods

Jul 18, 2024

Python List Methods

Overview

  • Covers 11 basic list methods in Python.
  • Excludes dunder methods.
  • Using dot notation to access methods.

Methods

1. Append

  • Usage: list.append(x)
  • Adds an element to the end of the list.
  • Example: people.append('Luigi') adds 'Luigi' to people.

2. Clear

  • Usage: list.clear()
  • Empties the list.
  • Example: people.clear() results in an empty list.

3. Copy

  • Usage: list.copy()
  • Creates a shallow copy of the list.
  • Example: copy_people = people.copy().
    • Changes to copy_people won't affect people.
    • Does not handle multi-dimensional lists correctly.

4. Count

  • Usage: list.count(x)
  • Counts the number of occurrences of an element in the list.
  • Example: people.count('Elon') returns the count of 'Elon' in people.

5. Extend

  • Usage: list.extend(iterable)
  • Extends the list by appending elements from an iterable.
  • Example: people.extend(['apple', 'banana']) adds 'apple' and 'banana' to people.

6. Index

  • Usage: list.index(x)
  • Returns the index of the first occurrence of an element.
  • Example: people.index('Trump') returns the index of 'Trump'.
  • Raises ValueError if the element is not found.

7. Insert

  • Usage: list.insert(i, x)
  • Inserts an element at a specified position.
  • Example: people.insert(1, 'Luigi') inserts 'Luigi' at index 1.
  • Handles boundary conditions (e.g., large positive or negative indices).

8. Pop

  • Usage: list.pop([i])
  • Removes and returns the element at a specified position (default is the last item).
  • Example: people.pop(0) removes and returns the first element.
  • The removed element can be stored for further processing.

9. Remove

  • Usage: list.remove(x)
  • Removes the first occurrence of an element.
  • Example: people.remove('Elon') removes the first 'Elon' in people.
  • Raises ValueError if the element is not found.

10. Reverse

  • Usage: list.reverse()
  • Reverses the order of the list in place.
  • Example: people.reverse() reverses the elements in people.

11. Sort

  • Usage: list.sort(key=None, reverse=False)
  • Sorts the list in place.
  • Example: people.sort() sorts people alphabetically.
    • Can specify a key for custom sort order.
    • reverse=True sorts in descending order.

Conclusion

  • These are the 11 basic list methods in Python.
  • Further customization can be done using keys and lambda functions.
  • Edge cases and handling multi-dimensional lists may require special attention.
  • Feedback and more tips are welcome.

End of Lecture.