Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Remove numbers with repeating digits

  • Difficulty Level : Medium
  • Last Updated : 28 Apr, 2022

Given a list of numbers, the task is to write a Python program to remove all numbers with repetitive digits.

Examples:

Input : test_list = [4252, 6578, 3421, 6545, 6676]

Output : test_list = [6578, 3421]

Explanation : 4252 has 2 occurrences of 2 hence removed. Similar case for all other removed.

Input : test_list = [4252, 6578, 3423, 6545, 6676]

Output : test_list = [6578]

Explanation : 4252 has 2 occurrences of 2 hence removed. Similar case for all other removed.

Method #1 : Using set() + len() + list comprehension

In this, we perform the task of eliminating repeating elements using set() and then compare the length to be equal to the original length. If found, True is returned, else False is returned.

Python3




# Python3 code to demonstrate working of
# Remove numbers with repeating digits
# Using set() + len() + list comprehension
 
# initializing list
test_list = [4252, 6578, 3421, 6545, 6676]
 
# printing original list
print("The original list is : " + str(test_list))
 
# set() used to remove digits
res = [sub for sub in test_list if len(set(str(sub))) == len(str(sub))]
 
# printing result
print("List after removing repeating digit numbers : " + str(res))

Output:

The original list is : [4252, 6578, 3421, 6545, 6676]
List after removing repeating digit numbers : [6578, 3421]

Method #2 : Using regex()

Appropriate regex can also be used for the task of checking for each digit repetition only once.

Python3




# Python3 code to demonstrate working of
# Remove numbers with repeating digits
# Using regex()
import re
 
# initializing list
test_list = [4252, 6578, 3421, 6545, 6676]
 
# printing original list
print("The original list is : " + str(test_list))
 
# regex used to remove elements with repeating digits
regex = re.compile(r"(\d).*\1")
res = [sub for sub in test_list if not regx.search(str(sub))]
 
# printing result
print("List after removing repeating digit numbers : " + str(res))

Output:

The original list is : [4252, 6578, 3421, 6545, 6676]
List after removing repeating digit numbers : [6578, 3421]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!