Remove_duplicates modifies the list that was passed to it


#1

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

def remove_duplicates(lst):
new_lst=[]
for i in lst:

     a= lst.remove(i)
     b=new_lst.append(a)

return b

Oops, try again. Your remove_duplicates modifies the list that was passed to it. [4, 5, 5, 4] was modified to [5, 4]. Perhaps you should make a copy first!


'int' object has no attribute 'getitem'
#2

Suggest try some other approach that does not use .remove().


#3

the output is not coming by .remove()


#4

def remove_duplicates(lst):

new_lst=[ ]

for i in lst:
   
    a=lst.remove(i)
    
return new_lst.append(a)

Oops, try again. Your remove_duplicates modifies the list that was passed to it. [4, 5, 5, 4] was modified to [5, 4]. Perhaps you should make a copy first!

kindly check this and telll me what is the prblm


#5

To repeat my earlier suggestion…

Your code contains most of the needed parts.

  1. a new list that is initialized to empty.
  2. a for loop to iterate the old list
  3. an if statement to check the old item against the new list (not quite)
  4. a return statement that sends the new list back to the caller.
def remove_duplicates(x):
    new_list = []    # notice no white space between brackets
    for i in x:
        if i not in new_list:
            new_list.append(i)
    return new_list

Note that we have not used list.remove()? We instead use the logical not to determine if the item is NOT in the new_list. If so, then it can be added. We do nothing to modify the original list.

You might do well to read up on the built in list method and see what it really does. It has no return value so a above will be None

>>> x = [4,5,5,4]
>>> x.remove(4)
>>> x
[5, 5, 4]
>>> a = x.remove(5)
>>> print (a)
None
>>> 

It should be noted as well that list.remove() is not selective but removes the first item that matches the argument. As such, the first 4, and first 5 are removed, leaving a list that is [5, 4] which raises the SCT error message. The method illustrated above using not in does not alter the order of the returned list since the first 4 and first 5 have already been examined and added to the new list. The second ones are ignored.


#6

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