Home > Enterprise >  Returning new list made from unique values of an existing list
Returning new list made from unique values of an existing list

Time:04-19

I want to make a new list from unique numbers of an old list but I with this code I can't append the singe occurrence of the values that repeat.

I found I can use set() but I want to try it this way also. The value I get by printing the following code is [5,4,3] but I want to have [1,2,5,4,3].

def unique_numbers(item):
    unique_list = []

    for num in item:
        unique = num
        counter = 0
        for num in item:
            if num == unique:
                counter  = 1
               
        if counter == 1:
            unique_list.append(unique)

    return unique_list
            
myList = [1,2,5,1,2,4,3,1,2]

unique = []
unique = unique_numbers(myList)
print(unique)

CodePudding user response:

Using a custom loop and list construction means that you are going have control over the order of items in the new list - i.e., the order is preserved. If you use a set, the order may be different.

Consider this:

L = [1,2,5,1,2,4,3,1,2]

def unique(list_):
    result = []
    for n in list_:
        if not n in result:
            result.append(n)
    return result

print(unique(L))
print(list(set(L)))

Output:

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

Note:

If the list is very large then the looped approach shown here will be woefully inefficient

Alternative:

def unique(list_):
    return list({k:None for k in list_})

CodePudding user response:

For that you don't need to use set.You created an empty list. You can go across through all elements and check the elments of list. If the element haven't repeated before append it in unique list. Like this :

def unique_numbers(my_list):
     # initialize a empty list
    unique_list = []
    # traverse all elements
    for x in my_list:
        # check if element is exists in unique_list or not
        if x not in unique_list:
            unique_list.append(x)
    for x in unique_list:
        # print list
        print(x),
my_list = [1,2,5,1,2,4,3,1,2]
unique_numbers(my_list)

 

Output : 1 2 5 4 3

  • Related