Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there is a repeated value in a list and get that value

How can I find the repeated value in a list? There will always be only one repeated value

for example:

numbers=[1,2,3,4,5,3]

I need to get the value 3

This is what I was trying but it is sometimes printing the value of the same list 2 times.

endLoop=False
    for n1 in range(0,len(numbers)):
        for n2 in range(1,len(numbers)):
            if numbers[n1]==numbers[n2]:
                print numbers
                print numbers[n1]
                endLoop=True
        if endLoop:
            break
like image 579
FutoRicky Avatar asked Dec 05 '25 13:12

FutoRicky


1 Answers

Keep track of numbers you have seen with a set() object, the first number that is already in the set is repeated:

def find_repeat(numbers):
    seen = set()
    for num in numbers:
        if num in seen:
            return num
        seen.add(num)

This is an efficient method to find the first repeated value, as it won't have to look at the rest of the numbers once it finds it.

like image 152
Martijn Pieters Avatar answered Dec 07 '25 06:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!