Python has a set of built-in methods that you can use on lists/arrays.
1) append(elmnt)
Adds an element at the end of the list
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
2) clear()
Removes all the elements from the list
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits) # []
3) copy()
Returns a copy of the list
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x) # ['apple', 'banana', 'cherry']
4) count(value)
Returns the number of elements with the specified value
arr = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = arr.count(9)
print(x) # 2
5) extend(iterable)
Add the elements of a list (or any iterable), to the end of the current list
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits) # ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
6) index(elmnt)
Returns the index of the first element with the specified value
numbers = [4, 55, 64, 32, 16, 32]
x = numbers.index(32)
print(x) # 3
7) insert(pos, elmnt)
Adds an element at the specified position
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits) # ['apple', 'orange', 'banana', 'cherry']
8) pop(pos)
Removes the element at the specified position
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits) # ['apple', 'cherry']
9) remove(elmnt)
Removes the first item with the specified value
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits) # ['apple', 'cherry']
10) reverse()
Reverses the order of the list
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits) # ['cherry', 'banana', 'apple']
11) sort(reverse=True|False, key=myFunc)
The sort() method sorts the list ascending by default.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars) # ['BMW', 'Ford', 'Volvo']
Top comments (0)