Skip to main content
Programming from zero

Arrays and lists theory + first problem: get the first and last server

easyLists Must-do

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.

flowchart LR A["index 0: web-01"] --> B["index 1: web-02"] --> C["index 2: db-01"] --> D["index 3: cache-01"] classDef first fill:#D1FAE5,stroke:#059669,color:#065F46 classDef middle fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef last fill:#FEF3C7,stroke:#D97706,color:#92400E class A first class B middle class C middle class D last
  • 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 is 4 - 1 = 3.

Common mistake: using the length itself as the last index.

TEXT
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:

TEXT
First: web-01
Last: cache-01

Approach

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]}")