Python Check if a variable is duplicate in a list

I want to see if there is a way to find out if a variable has an equivalent variable in the list.

a = 'hi'

b = 'ji'

c = 'ki'

d = 'li'

e = 'hi'

letters = [a, b, c, d, e]

      

Is there a way to check if any variable ( a

) is equal to any other variable ( e

). In this case, we return True

. Is there a faster way than just listing all combinations of comparative sentences?

+3


source to share


1 answer


You can try using the following -

len(letters) != len(set(letters))

      

When you convert a list to set, it removes the duplicate elements from the list, so if any element is present more than once, in letters the length set(letters)

will be less than the length of the original list and the above condition will return True

.




Example / Demo -

In [9]: a = 'hi'

In [10]: b = 'ji'

In [11]: c = 'ki'

In [12]: d = 'li'

In [13]: e = 'hi'

In [14]: letters = [a, b, c, d, e]

In [15]: len(letters) != len(set(letters))
Out[15]: True

In [16]: letters = [a,b,c,d]

In [17]: len(letters) != len(set(letters))
Out[17]: False

      

+4


source







All Articles