1

I have a list:

list = ["A", "A", "B", "A", "C"]

and a for and if statement combined:

for x in list:
    if "A" in x:
        print("true")

Output for the above code:

true
true

Next, I am figuring out how to tell me there is duplicates of "A" in list and return me value of True

Here is what i have tried:

for x in list:
    if any(x == "A" in x):
        return True

but an error shows up: SyntaxError: 'return' outside function

tried this too:

 for x in list:
    if any(x == "A" in x):
    return True
SyntaxError: expected an indented block

my desired output would be:

True because duplicates of "A" exists

sharks Tale
  • 135
  • 1
  • 8

4 Answers4

4

Can use Counter:

from collections import Counter

# hold in a 'dictionary' style something like: {'A':2, 'B':1, 'C':2}
c = Counter(['A','A','B', 'C', 'C'])

# check if 'A' appears more than 1 time. In case there is no 'A' in 
# original list, put '0' as default. 
c.get('A', 0) > 1 # 

>> True
Aaron_ab
  • 3,450
  • 3
  • 28
  • 42
1

return is used to return a value from function outside function block it wont work.

For a given list [1,2,3,4,1,1,3] .count(element) will return number of occurrences if it is greater than 1 you cam be sure that is has duplicates

You can try like this

for x in list:
    if "A" in x:
        print("true")
        print(list.count("A")) #count will return more that 1 if there are duplicates
Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
1

This code should do the trick:

def duplicate(mylist):
    for item in mylist:
        if mylist.count(item) > 1:
            return True
    return False
Legorooj
  • 2,646
  • 2
  • 15
  • 35
1

Return only works inside of a function.

Try this:

See here

def test(_list):
        d = {x:_list.count(x) for x in _list}
        result = [x for x in d.values()]
        if any(i > 1 for i in d.values()): 
            return True
        else: return False

_list = ["A", "A", "B", "A", "C"]  
print( test(_list) )
RightmireM
  • 2,381
  • 2
  • 24
  • 42