How i can i traverse a list and check if an equal item contains there?

I want to ask the user to input a list of strings such as : ["i", "love you" , "so much", "so much"] and check if a equal string contains there and print the strings that most appear in ascending order. I wanted to know how could i do this either using a map or two foor loops.

I tried doing with one foor loop but is ineficient since i can't do this the other way around. I need to do this using 2 foor lops or a map but i don't how to implement the logic. Can anyone help me? Thanks


Solution 1:

You can use a set for this. Sets cannot have duplicate elements, and thus if you convert a list to a set and the size of the list shrank, then there was a duplicate element. However, this only works if you do not care about which element was duplicated.

For example:

strings = ["i", "love you" , "so much", "so much"]
if len(strings) == len(set(strings)):
    print("No duplicates")
else:
    print("There was some duplicate")

Edit:

To address your comment of:

Is there a way i could print the frequency of those elements appear in the list too? Because in that way i can only now if there is a duplicate but not which duplicate it is. For example i want to print : "so much", "i", "love you".

Yes. You can use a Counter for this:

from collections import Counter
strings = ["i", "love you" , "so much", "so much"]
counted = Counter(strings)
print(counted)

which outputs

Counter({'so much': 2, 'i': 1, 'love you': 1})