0

I am new to this python language: I am facing issues to display the unique elements in the list in the following pgm: Below are my program:

def unique_list(lst):
    c = []
    for i in lst:
        if (lst.count(i)>=1) & i not in c:
            c.append(i)
            #print(c)
    return c  
print(unique_list([1,1,1,2,2,3,3,4,5]))

I received the output as:

[1,2,2,4] instead of [1,2,3,4,5]

i think there is a mistake in the if stmt... can anyone explain me y am i getting this output??

Geshode
  • 3,600
  • 6
  • 18
  • 32
Kousy
  • 1
  • 1
    You can use `set` ex: `print(set([1,1,1,2,2,3,3,4,5]))` – Rakesh Jul 11 '18 at 07:52
  • 1
    Use `and`, not `&`. – 9769953 Jul 11 '18 at 07:53
  • Hi, welcome to Stackoverflow. Most people here would greatly appreciate it if you would spend a bit more effort in asking your question. After all, it takes some effort to read and answer it, too. Examples include: Do not use hard-to-read abrreviations ("stmt", "pgm", "y"…), format your code, … – Lukas Barth Jul 11 '18 at 07:54
  • 1
    I don't think you need the first part in your if statement anyway: just `if i not in c` should be enough, since`i` will always be an element of `lst`, and thus `lst.count(i)` is always equal or larger than 1. – 9769953 Jul 11 '18 at 07:54

1 Answers1

0

You can get the unique elements in a list by transforming it into a set:

print(set([1,1,1,2,2,3,3,4,5]))
RustyBrain
  • 115
  • 1
  • 12