Arrays
What Is an Array?
- An array is a special variable that can hold multiple values at once. Python doesn't have built-in support for arrays, but lists can be used instead. For more advanced array operations, you can use the NumPy library.
Why Use Arrays?
- Arrays are useful for storing multiple items under a single name, making it easier to manage and access them using an index number.
Creating and Using Arrays (Lists) in Python:
- Creating an Array:
Example of creating an array containing car names:
pythoncars = ["Ford", "Volvo", "BMW"]
- Accessing Elements:
Access elements by referring to their index:
pythonprint(cars[0]) print(cars[1]) print(cars[2])Output:
Ford Volvo BMW
- Looping Through an Array:
Loop through the array to print all car names:
pythonfor car in cars: print(car)Output:
Ford Volvo BMW
- Adding Elements:
Add an element to the end of the array:
pythoncars.append("Audi") print(cars) # Output: ['Ford', 'Volvo', 'BMW', 'Audi']
- Removing Elements:
Remove an element from the array:
pythoncars.remove("Volvo") print(cars) # Output: ['Ford', 'BMW', 'Audi']
Exercises:
- Create and Print an Array:
- Create an array with the names of your favorite fruits. Print each fruit using a loop.
- Add and Remove Elements:
- Add two new fruits to your array and remove one fruit. Print the updated array.
- Access Specific Elements:
- Access and print the first and last elements of your fruit array.
Summary:
- Arrays (or lists in Python) are powerful tools for storing and managing multiple values. They simplify access and operations on collections of items. Practice creating, accessing, and modifying arrays to get comfortable with using them in your Python programs!