python 17 lines · 6 steps

Validating card numbers with the Luhn check

A digit-doubling checksum catches most mistyped or invalid card numbers.

Explained by highlit
1def is_valid_card_number(number: str) -> bool:
2 digits = [int(c) for c in number if c.isdigit()]
3 
4 if len(digits) < 13 or len(digits) > 19:
5 return False
6 
7 checksum = 0
8 parity = len(digits) % 2
9 
10 for index, digit in enumerate(digits):
11 if index % 2 == parity:
12 digit *= 2
13 if digit > 9:
14 digit -= 9
15 checksum += digit
16 
17 return checksum % 10 == 0
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The Luhn algorithm doubles every other digit and subtracts 9 when the result exceeds 9, which is equivalent to summing its digits.
  2. 2Deriving parity from the total length lets you double the correct positions no matter how many digits there are.
  3. 3A checksum that must be divisible by 10 catches most single-digit typos and simple transpositions cheaply.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating card numbers with the Luhn check — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code