List Methods
Python provides list methods that allow us to work with lists.
Let’s learn few among them
- append()
- extend()
- insert()
- pop()
- clear()
- remove()
- sort()
- index()
Append
list.append(value) Adds an element to the end of the list.
Code
list_a = []
for x in range(1,4):
list_a.append(x)
print(list_a)
Output
[1, 2, 3]
Extend
list_a.extend(list_b) Adds all the elements of a sequence to the end of the list.
Code
list_a = [1, 2, 3]
list_b = [4, 5, 6]
list_a.extend(list_b)
print(list_a)
Output
[1, 2, 3, 4, 5, 6]
Insert
list.insert(index,value) Element is inserted to the list at specified index.
Code
list_a = [1, 2, 3]
list_a.insert(1,4)
print(list_a)
Output
[1, 4, 2, 3]
Pop
list.pop() Removes last element.
Code
list_a = [1, 2, 3]
list_a.pop()
print(list_a)
Output
[1, 2]
Remove
list.remove(value) Removes the first matching element from the list.
Code
list_a = [1, 3, 2, 3]
list_a.remove(3)
print(list_a)
Output
[1, 2, 3]
Clear
list.clear() Removes all the items from the list.
Code
list_a = [1, 2, 3]
list_a.clear()
print(list_a)
Output
[]
Index
list.index(value) Returns the index at the first occurrence of the specified value.
Code
list_a = [1, 3, 2, 3]
index =list_a.index(3)
print(index)
Output
1
Count
list.count(value) Returns the number of elements with the specified value.
Code
list_a = [1, 2, 3]
count = list_a.count(2)
print(count)
Output
1
Sort
list.sort() Sorts the list.
Code
list_a = [1, 3, 2]
list_a.sort()
print(list_a)
Output
[1, 2, 3]
Sort & Sorted
sort() Modifies the list
Code
list_a = [1, 3, 2]
list_a.sort()
print(list_a)
Output
[1, 2, 3]
sorted() Creates a new sorted list
Code
list_a = [1, 3, 2]
sorted(list_a)
print(list_a)
Output
[1, 3, 2]