Arrays and Lists in Programming
What are Arrays and Lists?
An array or list is a collection of items stored in a single variable. These items are usually of the same type (in arrays) but can be of mixed types in lists (in languages like Python).
Think of an array/list as a row of boxes, each holding one piece of data. Each box has a position called an index, usually starting from 0.
Example: Storing the marks of 5 students:
-
marks[0]→ 80 -
marks[4]→ 70
Arrays and lists make it easy to store, access, and process multiple values efficiently.
Creating Arrays / Lists
Python (Lists)
Java (Arrays)
Java (ArrayList) – Dynamic lists
Accessing Elements
You can access individual items using their index:
Java:
Note: Indexing starts at 0, not 1.
Updating Elements
You can change a value at a specific index.
Python:
Java:
Adding and Removing Elements
Python (Lists)
Java (ArrayList)
Looping Through Arrays / Lists
You can process all items using loops.
Python Example:
Java Example (Array):
Java Example (ArrayList):
Common Operations on Arrays / Lists
| Operation | Python Example | Java Example (ArrayList) |
|---|---|---|
| Length / Size | len(numbers) |
fruits.size() |
| Check element in list | "apple" in fruits |
fruits.contains("apple") |
| Index of element | fruits.index("banana") |
fruits.indexOf("banana") |
| Sort | numbers.sort() |
Collections.sort(fruits) |
| Reverse | numbers.reverse() |
Collections.reverse(fruits) |
Multi-Dimensional Arrays / Lists
You can have lists or arrays inside lists, useful for tables, grids, or matrices.
Python Example (2D list):
Java Example (2D array):
Best Practices for Arrays / Lists
-
Use descriptive names:
marksinstead ofa. -
Use loops to process elements efficiently.
-
Avoid out-of-bounds errors by checking index limits.
-
Choose the right type: array for fixed size, list/ArrayList for dynamic size.
-
Use built-in functions for sorting, searching, or reversing for simplicity.
Summary
Arrays and lists are fundamental data structures in programming:
-
Store multiple items in a single variable.
-
Access items using index starting from 0.
-
Update, add, or remove items as needed.
-
Use loops to process elements efficiently.
-
Support multi-dimensional storage for grids and tables.
-
Arrays have fixed size (Java), lists are dynamic (Python, ArrayList in Java).
Mastering arrays and lists is essential because they allow programs to handle large amounts of data efficiently, making them a cornerstone of programming.