James Reid
James Reid

Reputation: 555

Display Loop from Database correctly Python

i would Like to display the word 'conflict' if the value is more than one in the list. this is my code

list = ['aa','bb','cc','aa']

conf = [s for s in list]

for a in list:
    if len(a in conf) > 1:
        print a, "-conflict"
    else:
        print a

I think my syntax is wrong in if len(a in conf)> 1: Please help me.

I am expecting this result:

aa - conflict
bb
cc
aa - conflict

Upvotes: 0

Views: 32

Answers (1)

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

You can use the count function.

if conf.count(a) > 1:
    print a, "-conflict"

The above method is similar to what you have tried. But this is inefficient when the list is large. So, use collections.Counter.

from collections import Counter
occurences = Counter(conf)
for a in list:
    if occurences[a] > 1:
        print a, "- conflict"
    else:
        print a

Upvotes: 1

Related Questions