Programming from zero

Store a server record as a tuple and access each value

easySets and tuples

Problem statement

A tuple groups a few related values into one fixed bundle, such as a server's name, IP and port: ("web-01", "10.0.0.5", 8080). Unlike a list, a tuple is meant for a small record where each position has its own meaning, and it cannot be changed after it is created.

Java has no built-in tuple. The closest simple equivalent is a record (Java 16 and newer): a small fixed group of values that you read by name. C++ has std::tuple.

Common mistake: trying to change a value inside a tuple.

TEXT
Wrong: server[2] = 9090

Python stops with a TypeError, because tuples cannot be modified. If the port really changes, build a new tuple with the new value. (Java records cannot be changed either. C++'s std::tuple can be, unless you make it const.)

Your task: store the server "web-01" with IP "10.0.0.5" and port 8080 as one tuple (or record), then print each value on its own labelled line.

Expected output:

TEXT
Name: web-01
IP: 10.0.0.5
Port: 8080

Approach

Create the record, then read each value:

  • Python: server[0], server[1], server[2] read by position, counting from 0 like a list.
  • Java: record Server(String name, String ip, int port) {} defines the record, then server.name(), server.ip() and server.port() read each value.
  • C++: std::get<0>(server), std::get<1>(server) and std::get<2>(server) read by position.

Python-only shortcut: you can unpack a tuple into separate variables in one line, name, ip, port = server. Remember the swap from the first section, active, standby = standby, active? That was tuple unpacking too.

DSA connection: tuples often hold pairs like (row, column) or (distance, node), so you will see them constantly in DSA problems.

server = ("web-01", "10.0.0.5", 8080)
print(f"Name: {server[0]}")
print(f"IP: {server[1]}")
print(f"Port: {server[2]}")