There are several ways and logics to find the number that is repeated in a list python.
Here is the linear solution for it.
import numpy as np
numbers = [1, 2, 3, 4, 2, 3, 5]
res = set([x for x in numbers if numbers.count(x) > 1])
print(res)
Output: {2, 3}
Python check if there is a repeated value in a list example
Simple example code.
Method 1
Using for-loop and if statement.
numbers = [1, 2, 3, 4, 2, 3, 5]
rep = []
for n in numbers:
if numbers.count(n) > 1:
if n not in rep:
print("Repeated number: ", n)
rep.append(n)
Output:
Method 2
It will find only the first repeated value.
numbers = [1, 2, 3, 4, 2, 3, 5]
endLoop = False
for n1 in range(0, len(numbers)):
for n2 in range(1, len(numbers)):
if numbers[n1] == numbers[n2] and n1 != n2:
print(numbers)
print(numbers[n1])
endLoop = True
if endLoop:
break
Output:
[1, 2, 3, 4, 2, 3, 5]
2
Method 3
Using set, it also finds first repeated values.
number = [1, 2, 3, 4, 2, 3, 5]
def find_repeat(numbers):
seen = set()
for num in numbers:
if num in seen:
return num
seen.add(num)
res = find_repeat(number)
print(res)
Method 4
Using NumPy, you have to import the NumPy module. But this is a different solution, where only counting a repetition of every element of the list.
import numpy as np
numbers = [1, 2, 3, 4, 2, 3, 5]
counts = np.bincount(numbers)
np.where([counts > 1])[1]
print(counts)
Output: [0 1 2 2 1 1]
Do comment if you have any questions or suggestions on this Python list tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.