Array Methods
Introduction:
- Python provides a set of built-in methods that you can use to manipulate lists (arrays). These methods make it easy to add, remove, and modify elements in your arrays.
Common Array Methods:
- append()
- Adds an element at the end of the list.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] cars.append("Honda") print(cars)- Output:
['Ford', 'Volvo', 'BMW', 'Honda']
- Output:
- clear()
- Removes all elements from the list.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] cars.clear() print(cars)- Output:
[]
- Output:
- copy()
- Returns a copy of the list.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] new_cars = cars.copy() print(new_cars)- Output:
['Ford', 'Volvo', 'BMW']
- Output:
- count()
- Returns the number of elements with the specified value.
Example:
pythonfruits = ["apple", "banana", "cherry", "apple"] print(fruits.count("apple"))- Output:
2
- Output:
- extend()
- Adds the elements of a list (or any iterable) to the end of the current list.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] more_cars = ["Honda", "Toyota"] cars.extend(more_cars) print(cars)- Output:
['Ford', 'Volvo', 'BMW', 'Honda', 'Toyota']
- Output:
- index()
- Returns the index of the first element with the specified value.
Example:
pythonfruits = ["apple", "banana", "cherry"] print(fruits.index("banana"))- Output:
1
- Output:
- insert()
- Adds an element at the specified position.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] cars.insert(1, "Honda") print(cars)- Output:
['Ford', 'Honda', 'Volvo', 'BMW']
- Output:
- pop()
- Removes the element at the specified position.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] cars.pop(1) print(cars)- Output:
['Ford', 'BMW']
- Output:
- remove()
- Removes the first item with the specified value.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] cars.remove("Volvo") print(cars)- Output:
['Ford', 'BMW']
- Output:
- reverse()
- Reverses the order of the list.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] cars.reverse() print(cars)- Output:
['BMW', 'Volvo', 'Ford']
- Output:
- sort()
- Sorts the list.
Example:
pythoncars = ["Ford", "Volvo", "BMW"] cars.sort() print(cars)- Output:
['BMW', 'Ford', 'Volvo']
- Output:
Exercises:
- Add and Remove Elements:
Create a list of numbers and add a new number at the end, then remove the first number.
pythonnumbers = [1, 2, 3, 4] numbers.append(5) numbers.remove(1) print(numbers)- Output:
[2, 3, 4, 5]
- Output:
- Copy and Clear List:
Copy a list of fruits and then clear the original list.
pythonfruits = ["apple", "banana", "cherry"] new_fruits = fruits.copy() fruits.clear() print(new_fruits) print(fruits)- Output:
['apple', 'banana', 'cherry'] - Output:
[]
- Output:
Summary:
- In this tutorial, we learned about various built-in methods to manipulate arrays in Python. These methods are essential for managing and processing data stored in arrays. Practice using these methods to get comfortable with array manipulation in Python!