Arrays and lists theory + first problem: get the first and last server
Problem statement
A list stores many values in one variable, in order. Instead of one variable per server, you keep them together: ["web-01", "web-02", "db-01", "cache-01"]. Each item has a position called its index, and counting starts at 0, not 1.
Java calls its fixed-size version an array, and C++ uses a vector. The idea is the same: an ordered row of values you reach by index.
- The first item is always at index
0. - The last item is at index
length - 1, where length is how many items the list holds. Here that is4 - 1 = 3.
Common mistake: using the length itself as the last index.
Wrong: servers[len(servers)] (index 4, but the last item is at index 3)With 4 items, the valid indexes are 0, 1, 2 and 3, so index 4 does not exist. Python and Java stop with an error. C++ does not check, so it may quietly read garbage, which makes this mistake even more important to avoid there.
Your task: given servers = ["web-01", "web-02", "db-01", "cache-01"], print the first server and the last server.
Expected output:
First: web-01Last: cache-01Approach
The first item is at index 0, and the last is at index length - 1. Each language asks for the length differently:
- Python:
len(servers) - Java:
servers.length(an array's size, no parentheses) - C++:
servers.size()
Python-only shortcut: servers[-1] also gives the last item, because Python lets you count backward from the end. Java and C++ do not support negative indexes, so learn the length - 1 way first.
DSA connection: array indexing, reading an item by its position, is the base of almost every array problem.
servers = ["web-01", "web-02", "db-01", "cache-01"]
print(f"First: {servers[0]}")
print(f"Last: {servers[len(servers) - 1]}")