Remove_duplicates


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/4?curriculum_id=4f89dab3d788890003000096


i got the error
"remove_duplicates([4, 5, 5, 4]) resulted in an error: 'int' object is not iterable"


it should remove repeating elements


def remove_duplicates(numbers):
    new_list=[]
    for i in range(0,len(numbers)):
        for j in range(0,i):
            if numbers[j]!= numbers[i]:
                new_list+=numbers[i]
    return new_list


#2

here:

new_list+=numbers[i]

using += for lists can be tricky, because it extends the list

lets have a look:

def remove_duplicates(numbers):
    new_list=[]
    for i in range(0,len(numbers)):
        for j in range(0,i):
            if numbers[j]!= numbers[i]:
                print new_list, numbers[i]
                new_list+=numbers[i]
    return new_list
        
print remove_duplicates([4,5,5,4])

so, you are trying to extend the list with 5, but extending the list requires an iterable

maybe you want to .append()?

I am not sure how your code is suppose to remove duplicates, could you explain? So i can see where you thought process might go wrong?


#3

in my code each number is compared with another using 2 for loops and if a match isn't found then that number is added in the new _list.


#4

that is possible, but not what you are currently doing, look:

def remove_duplicates(numbers):
    new_list=[]
    for i in range(0,len(numbers)):
        for j in range(0,i):
            if numbers[j]!= numbers[i]:
                new_list.append(numbers[i])
    return new_list
        
print remove_duplicates([4,5,5,4])

i use .append() rather then extending the list, maybe add some print statements so you can see your code is not behaving as it should?

What you attempt to do would require the following approach:

loop over numbers, for each number in numbers loop over new_list to see if the number is in new list (so two loops like you have now)

before the second for loop create a variable called not_in_list and set it true. If the number turns out to be in the list (if condition) set not_in_list to false

after the second loop, check the value of not_in_list to determine if you need to .append() number to new_list


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.