Home > other >  Removing duplicate numbers from the parameter list and then update it
Removing duplicate numbers from the parameter list and then update it

Time:06-05

I'm trying to remove any numbers which are repeated in the parameter list. I tried doing this but it doesn't seems to work. Any help is appreciated!! thanks so much

#Im not allowed to use set()

Here's my attempted code:

def remove_all_repeats(numbers_list):
    a_list = []
    for num in numbers_list:
        if num not in a_list:
            a_list.append(num)

    numbers_list = a_list


numbers = [3, 71, 71, 3, 99, 3, 67, 88]
remove_all_repeats(numbers)
print(numbers)

CodePudding user response:

Your function is correct, but numbers_list inside the function becomes a new local variable when you reassign its value to a_list. It is not modifying the numbers variable that you define outside the function. You have to return the value from the function like this:

def remove_all_repeats(numbers_list):
    a_list = []
    for num in numbers_list:
        if num not in a_list:
            a_list.append(num)

    numbers_list = a_list
    return numbers_list


numbers = [3, 71, 71, 3, 99, 3, 67, 88]
print(remove_all_repeats(numbers))

CodePudding user response:

many ways to do this; you can simply create a dictionary using the elements as keys and transform it back to list. This will remove duplicates.

numbers = [3, 71, 71, 3, 99, 3, 67, 88]
numbers = list(dict.fromkeys(numbers))

CodePudding user response:

The function doesn't work because numbers_list = a_list is basically just reference to a_list and the list that is previously referenced by numbers_list doesn't change. To fix the issue, you can have the function return the updated list and assign the returned value to the numbers list

def remove_all_repeats(numbers_list):
    a_list = []
    for num in numbers_list:
        if num not in a_list:
            a_list.append(num)

    return a_list

numbers = [3, 71, 71, 3, 99, 3, 67, 88]
numbers = remove_all_repeats(numbers)
print(numbers)

Alternatively, you can also update the numbers_list inside the function using the expression numbers_list[:] = a_list

def remove_all_repeats(numbers_list):
    a_list = []
    for num in numbers_list:
        if num not in a_list:
            a_list.append(num)

    numbers_list[:] = a_list

numbers = [3, 71, 71, 3, 99, 3, 67, 88]
remove_all_repeats(numbers)
print(numbers)

CodePudding user response:

since you are passing the list object and want to modify that list only then you can make a new list with unique element and use list.copy or list[:] to copy element of that list to your existing list.

def remove_all_repeats(numbers_list):
    a_list = []
    for num in numbers_list:
        if num not in a_list:
            a_list.append(num)

    numbers_list[:] = a_list
  • Related