Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
1 view
in Python by (1.6k points)

I want to get the unique values from the following list:

[u'hello', u'how', u'how', u'is', u'your', u'life', u'going']

The output I want is:

[u'hello', u'how', u'is', u'your', u'life', u'going']

I have used this code:

output = []

for x in trends:

    if x not in output:

     output.append(x)

print output

is there a better solution I should use?

1 Answer

0 votes
by (10.9k points)
edited by

You can get unique values by converting the list to a set first:

your_list = [u'hello', u'how', u'how', u'is', u'your', u'life', u'going']

your_set = set(your_list)

print(your_set)

You may covert the set to a list later using your_newlist = list(your_set)  in the above code.

Similarly, if you start with a set instead of a list use this code to get unique values:

output = set()

for x in trends:

    output.add(x)

print(output)

 

But remember, sets do not maintain the original order. To know more about the set order visit here:http://code.activestate.com/recipes/576694/

Related questions

Browse Categories

...