How to check if two numbers in a list are the same
python
Solution
If you want to use loops, you'll have to use a list or a set of numbers which you've already seen. Then while looping you'll check, with the `in` operator if the number is already seen.
seen = []
for number in myList:
if number in seen:
print "Number repeated!"
else:
seen.append(number)
`set` does not allow duplicates in it, thus it's a good fit for this sort of an algorithm. As mentioned in the comments, the time complexity for checking if an element is in a set is constant for the average case (O(1)), so this is more efficient if you have a lot of numbers.
seen = set()
for number in myList:
if number in seen:
print "Number repeated!"
seen.add(number) # won't duplicate
I'd say that the most pythonic way is to use `collections.Counter`, but the other answers cover this already. To use a built-in, you could generate a set of the numbers which appear more than once using a generator expression and `set`.
In [39]: seen = set()
In [40]: print list(set(x for x in myList if x in seen or seen.add(x)))
[1]
Here the expression will loop over all values in `myList` and add them to a `set` called `seen` if they have already been seen. Eventually, it will convert the resulting set into a list and print the contents.
Problem
I was curious on how I would check if 2 numbers inside of a list are identical. For instance, ``` myList=[1,7,9,3,1,2,8] ``` In this case, "1" is repeated in 'myList'. How would I make a program that checks to see if two numbers inside of a list are the same(repeated). Try to use loops so I can understand because I haven't yet learned complex functions.