Skip to content

Python List API

Python list methods — mutable ordered sequences for storing and manipulating collections.

1 class · 9 methods

list

9 methods

Mutable ordered sequence of arbitrary objects.

list.append(item)

Append item to the end of the list.

Parameters

NameTypeDescription
itemAnyItem to append.

Returns

None

Example

python
nums = [1, 2]
nums.append(3)
# nums == [1, 2, 3]
list.extend(iterable)

Extend the list by appending all items from iterable.

Parameters

NameTypeDescription
iterableIterableIterable whose items are appended.

Returns

None

Example

python
nums = [1, 2]
nums.extend([3, 4])
# nums == [1, 2, 3, 4]
list.insert(index, item)

Insert item before the given index.

Parameters

NameTypeDescription
indexintInsertion position.
itemAnyItem to insert.

Returns

None

Example

python
nums = [1, 3]
nums.insert(1, 2)
# nums == [1, 2, 3]
list.remove(item)

Remove the first occurrence of item. Raises ValueError if not found.

Parameters

NameTypeDescription
itemAnyItem to remove.

Returns

None

Example

python
nums = [1, 2, 1]
nums.remove(1)
# nums == [2, 1]
list.pop([index])

Remove and return item at index (default last). Raises IndexError if empty.

Parameters

NameTypeDescription
indexintIndex of item to remove (default -1).

Returns

Any

Example

python
nums = [1, 2, 3]
nums.pop()     # 3, nums == [1, 2]
nums.pop(0)    # 1, nums == [2]
list.sort(*, key=None, reverse=False)

Sort the list in place.

Parameters

NameTypeDescription
keyCallable | NoneFunction extracting sort key.
reverseboolSort descending if True.

Returns

None

Example

python
nums = [3, 1, 2]
nums.sort()
# nums == [1, 2, 3]

words = ['bb', 'a', 'ccc']
words.sort(key=len)
# words == ['a', 'bb', 'ccc']
list.reverse()

Reverse the list in place.

Returns

None

Example

python
nums = [1, 2, 3]
nums.reverse()
# nums == [3, 2, 1]
list.index(item[, start[, end]])

Return first index of item. Raises ValueError if not found.

Parameters

NameTypeDescription
itemAnyItem to find.
startintStart index.
endintEnd index.

Returns

int

Example

python
nums = [1, 2, 1]
nums.index(1)      # 0
nums.index(1, 1)   # 2
list.count(item)

Return the number of occurrences of item.

Parameters

NameTypeDescription
itemAnyItem to count.

Returns

int

Example

python
[1, 2, 1, 1].count(1)  # 3