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.
Using Count() method A simple count of how many times an element occurs in the list. If its occurrence count is equal to the length of the list, then it means all elements in the list are the Same i.e.
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.
Using list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.
Using collections.Counter
:
from collections import Counter
myList = [1, 7, 9, 3, 1, 2, 8]
counter = Counter(myList)
print(counter) # prints 'Counter({1: 2, 2: 1, 3: 1, 7: 1, 8: 1, 9: 1})'
With Collections.Counter
, you know how many times is repeated every element of your source list myList
.
After that you can use a simple list comprehension
to know which elements are repeated:
result = [i for i, j in counter.items() if j > 1]
print(result) # prints '[1]'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With