Python
Python List Methods
Python provides several built-in methods for the list
class that allow you to efficiently manipulate lists, access their data, and transform them.
List methods are built-in methods of the list
object, while functions are global Python functions that can be applied to lists.
Here is a list of some important Python list methods:
Method | Description |
---|---|
list.clear() |
Removes all elements from the list. Example: lst = [1, 2]; lst.clear() → [] |
list.copy() |
Returns a shallow copy of the list |
append(x) |
Adds element x to the end of the list. Example: lst = [1, 2]; lst.append(3) → [1, 2, 3] |
extend(iterable) |
Adds elements from an iterable. Example: lst = [1]; lst.extend([2, 3]) → [1, 2, 3] |
insert(i, x) |
Inserts x at position i . Example: lst = [1, 3]; lst.insert(1, 2) → [1, 2, 3] |
remove(x) |
Removes the first occurrence of x . Example: lst = [1, 5, 5]; lst.remove(5) → [1, 5] |
pop([i]) |
Removes and returns the element at index i . Example: lst = [1, 2, 3]; lst.pop(1) → 2, lst = [1, 3] |
index(x[, start[, end]]) |
Returns the index of the first occurrence of x . Example: lst = [1, 2, 2]; lst.index(2) → 1 |
count(x) |
Counts the number of occurrences of x . Example: lst = [1, 2, 2, 2]; lst.count(2) → 3 |
reverse() |
Reverses the order of elements. Example: lst = [1, 2, 3]; lst.reverse() → [3, 2, 1] |
sort(key=None, reverse=False) |
Sorts the list. Example: lst = [3, 1, 2]; lst.sort() → [1, 2, 3] |
Performance:
- Methods
append
andpop
operate in O(1). insert
,remove
, andpop(i)
operate in O(n), wheren
is the length of the list.- Sorting (
sort
,sorted
) operates in O(n log n), wheren
is the length of the list.
List methods are called using dot notation (e.g., lst.append(1)
).
Most methods (except index
, count
, copy
, and pop
) modify the list in place and do not return a new list.
Lists can contain elements of different types (numbers, strings, other lists, etc.), but for sort
, all elements must be comparable.
Built-in Functions for Working with Lists
The following built-in functions can be used with lists.
Function | Description |
---|---|
list() |
Creates a new empty list |
list(iterable) |
Creates a list from an iterable. Example: list("abc") → ['a', 'b', 'c'] |
list(range(count)) |
Creates a list filled with sequential numbers starting from zero. Example: list(range(3)) → [0, 1, 2] |
list(range(first, end)) |
Creates a list filled with sequential numbers starting from first . Example: list(range(3, 6)) → [3, 4, 5] |
len(list) |
Returns the length of the list (number of elements). Example: len([1, 2, 3]) → 3 |
max(list) |
Finds the maximum element. Example: max([1, 2, 3]) → 3 |
min(list) |
Finds the minimum element. Example: min([1, 2, 3]) → 1 |
sum(list) |
Sums the elements (for numeric lists). Example: sum([1, 2, 3]) → 6 |
str(list) |
Returns a string representation of the list for printing. Example: str([1, 2, 3]) → '[1, 2, 3]' |
type(variable) |
Returns the type of the given variable. If the variable is a list, it returns <class 'list'> |
isinstance(list) |
Checks if an object is a list. Custom subclasses of lists also return True . Example: isinstance([1, 2, 3], list) → True |
tuple(list) |
Converts a list to a tuple. Example: tuple([1, 2, 3]) → (1, 2, 3) |
iter(list) |
Returns an iterator over the list |
reversed(list) |
Returns an iterator over the list in reverse order. Example: lst = [1, 2, 3]; list(reversed(lst)) → [3, 2, 1] |
enumerate(list, start=0) |
Returns an iterator of (index, element) pairs. The start parameter sets the starting index (default is 0). Often used in for loops to access both indices and elements. Example: lst = ['a', 'b']; list(enumerate(lst)) → [(0, 'a'), (1, 'b')] |
sorted(list, key=None, reverse=False) |
Returns a new sorted list. Example: lst = [3, 1, 2]; sorted(lst) → [1, 2, 3] |
all(list) |
Checks if all elements are true. Example: lst = [True, True]; all(lst) → True |
any(list) |
Checks if at least one element is true. Example: lst = [False, True]; any(lst) → True |
Operators That Work with Lists
Operator | Description |
---|---|
in |
Checks if an element is in the list. Example: lst = [1, 2, 3]; 2 in lst → True |
not in |
Checks if an element is not in the list. Example: lst = [1, 2, 3]; 4 not in lst → True |
Performance: O(n), as it checks each element.
Python list methods provide a powerful and flexible toolkit for working with data. For more complex operations, additional modules like collections
or libraries such as numpy
are often used.
Frequently Asked Questions About Python List Methods
What’s the difference between clear()
and assigning []
?
The difference between the clear()
method and assigning []
to a list lies in how they affect the list object and its references in memory.
my_list.clear()
removes all elements from the existing list object. The list object itself remains the same (i.e., its memory identifier doesn’t change). The list becomes empty, but it’s still the same object that other variables might reference.
Assigning my_list = []
creates a new empty list and assigns it to the variable. If other variables were referencing the old list, they remain tied to the old object. If there are no more references to the old list, it will be garbage-collected.
What’s the Difference Between Copying and Cloning a List?
In the context of Python lists, “copying” and “cloning” are often used interchangeably, but there are subtle distinctions:
- Copying typically refers to creating a shallow copy.
- Cloning often implies creating a deep copy.