Python Array Methods
Python lists (often used as arrays) come with many built-in methods that make it easy to manage, modify, and analyze data stored in them.
Below is a rewritten explanation of common array methods, along with updated and original examples.
Common Array Methods
append() – Add an Item to the End
Adds a single element at the end of the list.
Output:
clear() – Remove All Elements
Deletes all items from the list, making it empty.
Output:
copy() – Create a Shallow Copy
Returns a new list with the same elements.
Output:
count() – Count Occurrences of a Value
Returns how many times a value appears in the list.
Output:
extend() – Add Multiple Elements
Adds elements from another iterable to the end of the list.
Output:
index() – Find Position of an Element
Returns the index of the first occurrence of a value.
Output:
insert() – Add an Element at a Specific Position
Inserts an element at the given index.
Output:
pop() – Remove an Element by Index
Removes and returns the element at the given position.
Output:
['exercise', 'sleep']
remove() – Remove an Element by Value
Removes the first matching value from the list.
Output:
reverse() – Reverse the List Order
Reverses the elements of the list in place.
Output:
sort() – Sort the List
Sorts the list in ascending order by default.
Output:
Sorting in descending order:
Output:
Summary of Array Methods
| Method | Purpose |
|---|---|
append() |
Add item at the end |
clear() |
Remove all elements |
copy() |
Create a duplicate list |
count() |
Count occurrences |
extend() |
Add multiple items |
index() |
Find element position |
insert() |
Add item at specific index |
pop() |
Remove item by index |
remove() |
Remove item by value |
reverse() |
Reverse list order |
sort() |
Sort list elements |
