Vermillion Vermillion - 1 month ago 7
Python Question

Check if list contains only and all numbers from 1 to 9, with no duplicates

If I have a list:

[6, 7, 4, 8, 9, 5, 3, 2, 1]


I want to make sure that every number from 1 to 9 is in the list, with no repeats, and no other numbers. What's the best way to do this?

Answer

This is a good way to solve this type of problem:

By sorting the list, and comparing equality against a list ranging from 1 - 9, you will cover all cases per the requirement of all numbers 1 to 9 with no duplicates:

sorted(my_list) == list(range(1, 10))

Demo:

>>> my_list = [1,2,3,4,5,6,7,8,9]
>>> sorted(my_list) == list(range(1, 10))
True

>>> my_list = [1,2,3,4,5,6,7,9,9]
>>> sorted(my_list) == list(range(1, 10))
False

>>> my_list = [1,2,3,4,5,6,7]
>>> sorted(my_list) == list(range(1, 10))
False