Programming from zero

Filter a list to only web servers

easyLists Must-do

Problem statement

An inventory lists all hosts: hosts = ["web-01", "db-01", "web-02", "cache-01", "web-03"]. Build a new list with only the hosts whose names start with web-, and print them separated by commas:

Web servers: web-01, web-02, web-03

Examples

Example 1

Input: hosts = ["web-01", "db-01", "web-02", "cache-01", "web-03"]

Output: Web servers: web-01, web-02, web-03

Hints

Approach

Optimal

Filtering means building a new list that keeps only the items that pass a test. Start with an empty list, loop over the original, and call .append() for each item that matches. The string method .startswith("web-") is the test here. To print the result nicely, ", ".join(web) glues the items together with a comma and a space between them. Once this pattern feels natural, you can write the same thing in one line as a list comprehension: [h for h in hosts if h.startswith("web-")].

Python
hosts = ["web-01", "db-01", "web-02", "cache-01", "web-03"]
web = []
for host in hosts:
if host.startswith("web-"):
web.append(host)
print("Web servers: " + ", ".join(web))

Follow-up questions

  • Rewrite the loop as a list comprehension.
  • Print how many hosts are *not* web servers.

Frequently asked questions

Removing items from a list while looping over it skips elements and causes subtle bugs. Building a new list is safer and keeps the original data intact.