Python function that takes a list and returns a new list with unique elements of the first list

Question:

I’m trying to solve this problem by using this code

def unique_list(numbers):
    unique = []
    for item in numbers :
        if item in unique == False:
            unique.append(item)
    return unique   

But every time i’m calling this function, I get an empty list
Can somebody help thus beginner ? I don’t understand where i’m going wrong

Asked By: Vardhan Palod

||

Answers:

Edit:

Actually, as pointed out by DeepSpace below, this is wrong! Curiously, It isn’t evaluated as (item in unique) == False nor as item in (unique == False).

It’s caused by operator precedence. In the line:

item in unique == False:

Python first resolves the unique == False expression, which checks if the variable unique is equals to False (which isn’t true, it is a list).

So, that line becomes

if item in False:

So, the if block is never executed! To fix it, you can wrap item in unique in parenthesis, such as:

if (item in unique) == False:

BUT, there’s a very useful data structure in Python that serves your purpose: Set. A Set holds only unique values, and you can create it from a existing list! So, your function can be rewritten as:

def unique_list(numbers):
   return list(set(numbers)) # It converts your original list into a set (with only unique values) and converts back into a list
Answered By: PauloRSF

As Oksana mentioned, use list(set(numbers)).
As for you code, change if item in unique == False to if item not in unique. But note that this code is slower, since it has to scan the list for every new element that it tries to add:

def unique_list(numbers):
    unique = []
    for item in numbers :
        if item not in unique:
            unique.append(item)
    return unique

print(unique_list([1, 2, 3, 1, 2]))
# [1, 2, 3]
Answered By: Timur Shtatland

We cannot check if the item in unique is false or true like that, instead we use ‘not’. Try this:

if not item in unique:
      unique.append(item)
Answered By: Riya Singh

As SET only contain unique value, we can use it to get your answer.

Use this python function code

def unique_list(numbers):
 x=set(numbers)           #unique numbers in set
 y=list(x)                #convert set to list as you want your output in LIST.
 print(y)

EXAMPLE:

unique_list([2,2,3,3,3])

OUTPUT Will be a unique list.

[2,3]
Answered By: Raushan kumar
def unique_list(lst):
    a = set(lst) 
    return list(a)
Answered By: Pavlo Radchenko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.