Filter a list to only web servers
Problem statement
Filtering means keeping only the items that match a rule. The safe pattern is to start with a new, empty list, loop through the original, and add an item to the new list only when it matches. Here the rule is: the name starts with web.
Common mistake: removing items from the list you are looping over.
Wrong:for name in servers: if not name.startswith("web"): servers.remove(name)When an item is removed, everything after it shifts one place left, so the loop jumps over the next item and never checks it. Building a new list leaves the original untouched and avoids the problem.
Your task: given servers = ["web-01", "db-01", "web-02", "cache-01", "web-03"], build a new list containing only the names that start with web, then print each one on its own line.
Expected output:
web-01web-02web-03Approach
Loop through servers, check each name, and add matches to web_servers. Each language spells "starts with" and "add to the end" differently:
- Python:
name.startswith("web")andweb_servers.append(name) - Java:
name.startsWith("web")andwebServers.add(name), using anArrayListbecause plain arrays cannot grow - C++:
name.substr(0, 3) == "web"(the first 3 characters equalweb) andwebServers.push_back(name)
DSA connection: looping through every item once and deciding what to do with each is called array traversal.
servers = ["web-01", "db-01", "web-02", "cache-01", "web-03"]
web_servers = []
for name in servers:
if name.startswith("web"):
web_servers.append(name)
for name in web_servers:
print(name)