Can i make this 14/15 code better, without using built-in functions?


#1

here is my code for 14/15, was wondering if this can get any better, without using split() etc.

def remove_duplicates(idk):
  str=[] #Empty list
  for x in idk: #iterating in original list
    if x in str: #checking for duplicates in the new list
      continue
    else:
      str.append(x)
  return str

#2

you don’t use split?


#3

no, like when i was making that remove_duplicates function, i didn’t know about the split() function, until i checked in the hints after completing the course, and i think it wasn’t explained beforehand too.
So, i thought as a complete newbie (as myself) without knowing about it (split() ) ,is there a more better way to do it without using split() ?


#4

split() is a great function, but not for remove_duplicates. The solution you have is better

although, i would use not keyword so you can just have an if condition, which checks if x not in str, then append x to str, which is much cleaner. You can get rid of continue and else keyword then


#5

Didn’t know about ‘not in’…

def remove_duplicates(idk):
  str=[] #Empty list
  for x in idk: 
    if x not in str:
      str.append(x)
  return str

checked it out!
Thats nice! :grin:
Thanks for suggesting that!!


#6

you should know not, it has been taught. On the other hand, continue hasn’t been taught yet

the combination of not and in hasn’t been taught, but sometimes you have to connect the dots yourself :wink:


#7

i have some experience with C , so i thought by any chance Python will too have ‘continue’ as it already has ‘break’… and turns out it has!! :smiley:
i got that code on my own after some million tries… trial/error :joy:


#8

This is risky …

str=[]

str is the name of a built-in function. It is best not to use the name of a built-in function as the name of a variable or other object. If you needed to call that function after you used its name for something else, you would not be able to do so conveniently.


#11

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