Find duplicate tracks in a playlist

A small Python project with a working offline example.

Repeated songs are a common playlist-cleanup problem. A track URI identifies a song; it cannot tell you where the song occurs in a playlist. This script reports the positions of repeated tracks without editing the playlist.

Try it without Spotify

Download playlist-audit.py

Run the downloaded file with Python 3.11 or newer. The default mode uses five synthetic entries, including one unavailable item and one episode.

Terminal
python playlist-audit.py

The fixture reports one extra occurrence: the same track at positions 1 and 4. The unavailable entry still occupies position 2. Episodes are counted separately.

Python
{
  "scanned": 5,
  "truncated": false,
  "unavailable": 1,
  "non_tracks": 1,
  "extra_occurrences": 1,
  "duplicates": [
    {
      "uri": "spotify:track:33XUHrCbrAW6me9ewdCZip",
      "positions": [
        1,
        4
      ]
    }
  ]
}

Scan a playlist you can access

Install the published library in a virtual environment, then pass your own playlist URL or URI. The default scan reads at most 100 entries plus one to determine whether the result is partial. A partial report cannot establish that the rest of the playlist contains no duplicates.

Terminal
python -m pip install spotapi==2.1.3
python playlist-audit.py --playlist "YOUR_PLAYLIST_URI" --limit 100

Access depends on Spotify. Use the read-only example only for resources you are permitted to access; the script neither signs into an account nor removes tracks.

Why the algorithm works

A dictionary maps each track URI to its occurrence positions. Building the dictionary takes one pass through the scan. A group with three positions contains two extra occurrences, rather than three. The iterator is closed even when the scan stops at its limit.

Read the complete Python source
Python
"""Find repeated track occurrences without modifying a playlist.

Run with no arguments for an offline demonstration.
For an accessible playlist: python playlist-audit.py --playlist URI --limit 100
Requires SpotAPI 2.1.3 only for a network scan.
"""
from __future__ import annotations

import argparse
import asyncio
import json
from contextlib import aclosing

FIXTURE = [
    "spotify:track:33XUHrCbrAW6me9ewdCZip",
    None,
    "spotify:track:5W3cjX2J3tjhG8zb6u0qHn",
    "spotify:track:33XUHrCbrAW6me9ewdCZip",
    "spotify:episode:33XUHrCbrAW6me9ewdCZip",
]


def summarize(uris: list[str | None], *, truncated: bool = False) -> dict:
    positions: dict[str, list[int]] = {}
    unavailable = non_tracks = 0
    for position, uri in enumerate(uris, 1):
        if not uri:
            unavailable += 1
        elif not uri.startswith("spotify:track:"):
            non_tracks += 1
        else:
            positions.setdefault(uri, []).append(position)
    duplicates = [
        {"uri": uri, "positions": indices}
        for uri, indices in positions.items() if len(indices) > 1
    ]
    return {
        "scanned": len(uris),
        "truncated": truncated,
        "unavailable": unavailable,
        "non_tracks": non_tracks,
        "extra_occurrences": sum(len(group["positions"]) - 1 for group in duplicates),
        "duplicates": duplicates,
    }


async def scan(playlist: str, limit: int) -> dict:
    from spotapi import Public

    uris = []
    async with aclosing(Public.iter_playlist_items(playlist)) as entries:
        async for entry in entries:
            if len(uris) == limit:
                return summarize(uris, truncated=True)
            uris.append(entry.uri)
    return summarize(uris)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--playlist", help="Accessible playlist ID, URI or full URL")
    parser.add_argument("--limit", type=int, default=100, choices=range(1, 1001),
                        metavar="1..1000")
    args = parser.parse_args()
    if args.playlist:
        result = asyncio.run(scan(args.playlist, args.limit))
    else:
        result = summarize(FIXTURE[:args.limit], truncated=len(FIXTURE) > args.limit)
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()

Extend the project

Keep the report read-only. Try exporting it to a file, or adding a unit test for three occurrences of one track. Read the playlist occurrence example and the identity explanation before extending the data model.

If this saved you time, star SpotAPI to help other Python developers find it. Share your adaptation or a reproducible question on Discord.