list
9 methodsMutable ordered sequence of arbitrary objects.
list.append(item)Append item to the end of the list.
Parameters
| Name | Type | Description |
|---|---|---|
| item | Any | Item 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
| Name | Type | Description |
|---|---|---|
| iterable | Iterable | Iterable 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
| Name | Type | Description |
|---|---|---|
| index | int | Insertion position. |
| item | Any | Item 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
| Name | Type | Description |
|---|---|---|
| item | Any | Item 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
| Name | Type | Description |
|---|---|---|
| index | int | Index 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
| Name | Type | Description |
|---|---|---|
| key | Callable | None | Function extracting sort key. |
| reverse | bool | Sort 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
| Name | Type | Description |
|---|---|---|
| item | Any | Item to find. |
| start | int | Start index. |
| end | int | End index. |
Returns
int
Example
python
nums = [1, 2, 1]
nums.index(1) # 0
nums.index(1, 1) # 2list.count(item)Return the number of occurrences of item.
Parameters
| Name | Type | Description |
|---|---|---|
| item | Any | Item to count. |
Returns
int
Example
python
[1, 2, 1, 1].count(1) # 3