Remove_duplicates


#1


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

Code error: 'int' object is not iterable


Hello,
I'm not sure what's wrong with my code, any help is appriciated!

Write a function remove_duplicates that takes in a list and removes elements of the list that are the same.


def remove_duplicates(lst):
    newlst =[]
    for element in lst:
        n= 0
        while n != max(len(lst)):
            if element != lst[n]:
                n+=1
            else:
                break
        newlist.append(element)
    return newlst


#2

First thing I see is that you're appending to newlist, when you set your empty list to newlst.


#3

But I want to append to newlst, because it should be the lst without dublicates


#4

You never set newlst to an empty list, but you did make newlist an empty list. It seems like you're making the code much more complicated than it needs to be as well. Why not just iterate though each item in the given list, check to see if it's in your new list, and if it's not append it? That gets rid of the while statement.


#5

@objectslayer91487 I think you're iterating in a long way. You can try like this:

def remove_duplicates(lst):
new_lst = []
for i in range(len(lst)):
element = lst[i]
if element not in new_lst:
new_lst.append(element)
return new_lst

I didn't know about the 'not in' operator and spent good 30 minutes of my time going through forums and what not. Hope I helped. :slight_smile:


#6

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