Get the first and last server in a list
Problem statement
Given servers = ["web-01", "web-02", "web-03", "web-04"], print the first server, the last server, and how many there are, as three lines: First: web-01, Last: web-04, Count: 4.
Examples
Example 1
Input: servers = ["web-01", "web-02", "web-03", "web-04"]
Output: First: web-01
Last: web-04
Count: 4
Hints
Approach
Optimal
A list stores several values in order, written inside square brackets. You read one item with its index in square brackets, and indexes start at 0, so servers[0] is the first item. Negative indexes count from the end: servers[-1] is always the last item, however long the list is. The built-in len() returns how many items the list holds. These three operations come up in almost every script that handles a list of hosts.
servers = ["web-01", "web-02", "web-03", "web-04"] print(f"First: {servers[0]}")print(f"Last: {servers[-1]}")print(f"Count: {len(servers)}")Follow-up questions
- Print the first two servers with the slice
servers[:2]. - Add
web-05withservers.append("web-05")and print the count again.
Frequently asked questions
You asked for a position that does not exist, for example servers[4] in a list of four items (valid indexes are 0 to 3). It also happens if the list is empty, so check len() first when a list might be empty.