Python
String Manipulation
Programming
Code Snippets
String Comparison

Check if string ends with one of the strings from a list

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, the cleanest way to check whether a string ends with any value from a list is usually str.endswith(). The important detail is that endswith accepts a tuple of suffixes, so you normally convert your list first and let Python handle the comparison logic directly.

The Simplest Solution

str.endswith() can take either:

  • a single suffix string
  • a tuple of suffix strings

So if you already have a list, convert it to a tuple.

python
1name = "report.csv"
2suffixes = [".csv", ".tsv", ".json"]
3
4matches = name.endswith(tuple(suffixes))
5print(matches)  # True

This is the most direct and idiomatic answer in Python.

Why a Tuple and Not a List

People often try this first:

python
name.endswith([".csv", ".json"])

That fails because endswith() expects a string or a tuple of strings, not a list.

The fix is simple:

python
name.endswith(tuple([".csv", ".json"]))

If the suffix list is already stable, you can just define it as a tuple from the start.

python
valid_suffixes = (".csv", ".tsv", ".json")

That avoids repeated conversion in tight loops.

Case Sensitivity

endswith() is case-sensitive. If you are checking filenames or user input where case should not matter, normalize both sides.

python
1name = "PHOTO.JPG"
2suffixes = [".jpg", ".png"]
3
4matches = name.lower().endswith(tuple(s.lower() for s in suffixes))
5print(matches)  # True

This is common for extension checks, especially on systems where filenames may vary in case.

Be careful with locale-sensitive text rules in general string processing, but for file extensions .lower() is usually fine.

Compare to a Manual Loop

You can also write the logic with any():

python
1name = "report.csv"
2suffixes = [".csv", ".tsv", ".json"]
3
4matches = any(name.endswith(suffix) for suffix in suffixes)
5print(matches)

This is readable and flexible. It becomes useful when you need custom matching logic, such as stripping whitespace or skipping empty suffixes.

Still, if all you need is "ends with one of these literal suffixes," endswith(tuple(...)) is shorter and usually clearer.

File Extension Use Cases

A common reason for this check is file filtering.

python
1files = ["a.csv", "b.txt", "c.json", "d.png"]
2suffixes = (".csv", ".json")
3
4selected = [name for name in files if name.endswith(suffixes)]
5print(selected)  # ['a.csv', 'c.json']

This is a good fit for:

  • import pipelines
  • CLI tools
  • cleanup scripts
  • media scanners

If you are already using pathlib, consider whether Path.suffix is clearer than endswith().

python
1from pathlib import Path
2
3path = Path("archive.tar.gz")
4print(path.suffix)   # .gz
5print(path.suffixes) # ['.tar', '.gz']

For multi-part extensions, suffixes may be more precise than a plain string test.

Empty Lists and Edge Cases

If the suffix list is empty, the result should usually be False.

python
1name = "report.csv"
2suffixes = []
3
4print(name.endswith(tuple(suffixes)))  # False

That behavior is sensible, but if an empty configuration means "accept everything" in your application, handle that explicitly.

python
1def ends_with_any(text: str, suffixes: list[str]) -> bool:
2    if not suffixes:
3        return True
4    return text.endswith(tuple(suffixes))

Do not rely on accidental semantics when configuration may be empty or malformed.

Performance Notes

For small suffix lists, performance differences are negligible. If the same suffix set is reused many times, store it as a tuple once:

python
VALID_SUFFIXES = (".csv", ".json", ".xml")

That avoids rebuilding a tuple on every call.

If matching rules become complex, such as wildcards or patterns, use regex or fnmatch instead of forcing everything through endswith().

Common Pitfalls

  • Passing a list directly into str.endswith() instead of a tuple.
  • Forgetting that matching is case-sensitive.
  • Using endswith() when the real requirement is pattern matching, not literal suffix matching.
  • Recomputing the tuple repeatedly in hot code paths without need.
  • Treating multi-part extensions such as .tar.gz as if they were always a single simple suffix case.

Summary

  • In Python, use text.endswith(tuple_of_suffixes) to check against multiple suffixes.
  • Convert lists to tuples before passing them to endswith().
  • Normalize case first if the comparison should be case-insensitive.
  • Use any() only when you need custom per-suffix logic.
  • For path-heavy code, consider pathlib when extension semantics matter.

Course illustration
Course illustration

All Rights Reserved.