📚 Reference guide

Lists: Store and Filter a Set of Items

Build a list of sample file names, keep only the .log entries, and read the first and last matches.

Series: Python for small scripts

Based on the official Python documentation. Date checked: November 27, 2026. Script tested on Python 3.13.5.

Series: Python for small scripts, Part 5 of 10. Previous: Part 4: Loops with for and while. Next: Part 6: Dictionaries: Keys, Values, and Lookup.

TL;DR

Before you start

The finished script

Save this as logs.py in that folder:

names = ["app.log", "auth.log", "cron.log", "debug.txt"]

logs = []
for name in names:
    if name.endswith(".log"):
        logs.append(name)

print(logs)
print("Count:", len(logs))
print("First:", logs[0])
print("Last:", logs[-1])

When you run it, you should see:

['app.log', 'auth.log', 'cron.log']
Count: 3
First: app.log
Last: cron.log

Steps

  1. Save and run the script. Change into python-scripts and run python3 logs.py. Why: you can see the filtered list before you change the names. You should see: the four lines above. debug.txt is absent because it does not end with .log.
  2. Read the empty list and append. logs = [] starts an empty list. name.endswith(".log") is true for the first three names, and logs.append(name) adds each match to the end. Why: you can build a shorter list from a longer one without editing the original names list.
  3. Read len, [0], and [-1]. len(logs) is the number of items, here 3. Indexes start at 0, so logs[0] is the first item. logs[-1] is the last item. Why: these are the usual ways to count a list and to read either end.
  4. A short note on tuples. A tuple uses parentheses, for example pair = ("app.log", 12). You can read pair[0], but you cannot assign to it. A line such as pair[0] = "auth.log" raises TypeError: 'tuple' object does not support item assignment. Use a list when the contents may change.

If it fails

Traceback (most recent call last):
  File "indexerror.py", line 2, in <module>
    print(logs[3])
          ~~~~^^^
IndexError: list index out of range

Print len(logs) first, and remember that the last valid index is len(logs) - 1.

Stay safe

Next

Part 6: Dictionaries: Keys, Values, and Lookup

Sources

Spot something wrong or outdated? Leave a comment below. Every comment is reviewed to keep these posts accurate.

By commenting, you agree to our Terms of use and confirm this is your own work. Short quotes are fine with a credit and link. Copied, unsafe, or abusive comments are removed. See something copied? Say so here.