Python List Built-in functions
Table of Content:
Python provides the following built-in functions, which can be used with the lists.
SN | Function | Description | Example |
---|---|---|---|
1 | cmp(list1, list2) | It compares the elements of both the lists. | This method is not used in the Python 3 and the above versions. |
2 | len(list) | It is used to calculate the length of the list. |
L1 = [1,2,3,4,5,6,7,8] print(len(L1)) 8 |
3 | max(list) | It returns the maximum element of the list. |
L1 = [12,34,26,48,72] print(max(L1)) 72 |
4 | min(list) | It returns the minimum element of the list. |
L1 = [12,34,26,48,72] print(min(L1)) 12 |
5 | list(seq) | It converts any sequence to the list. |
str = "Johnson" s = list(str) print(type(s)) <class list> |
Python List/Array Methods
Sr. No. | Method | Description | Example |
---|---|---|---|
1 | append() | Adds an element at the end of the list | my_list = [1, 2, 3] my_list.append(4) print(my_list) Output: [1, 2, 3, 4] |
2 | clear() | Removes all the elements from the list | my_list = [1, 2, 3] my_list.clear() print(my_list) Output: [] |
3 | copy() | Returns a copy of the list | my_list = [1, 2, 3] new_list = my_list.copy() print(new_list) Output: [1, 2, 3] |
4 | count() | Returns the number of elements with the specified value | my_list = [1, 2, 2, 3, 2] count = my_list.count(2) print(count) Output: 3 |
5 | extend() | Add the elements of a list (or any iterable) to the end of the current list | my_list = [1, 2, 3] my_list.extend([4, 5]) print(my_list) Output: [1, 2, 3, 4, 5] |
6 | index() | Returns the index of the first element with the specified value | my_list = [1, 2, 3, 2] index = my_list.index(2) print(index) Output: 1 |
7 | insert() | Adds an element at the specified position | my_list = [1, 2, 3] my_list.insert(1, 4) print(my_list) Output: [1, 4, 2, 3] |
8 | pop() | Removes the element at the specified position | my_list = [1, 2, 3] element = my_list.pop(1) print(element) Output: 2 |
9 | remove() | Removes the first item with the specified value | my_list = [1, 2, 3, 2] my_list.remove(2) print(my_list) Output: [1, 3, 2] |
10 | reverse() | Reverses the order of the list | my_list = [1, 2, 3] my_list.reverse() print(my_list) Output: [3, 2, 1] |
11 | sort() | Sorts the list | my_list = [3, 1, 2] my_list.sort() print(my_list) Output: [1, 2, 3] |