Skip to content

Instantly share code, notes, and snippets.

@redrambles
Last active July 22, 2021 03:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save redrambles/c099b771a76e7ade81b5fb463b72126b to your computer and use it in GitHub Desktop.
Save redrambles/c099b771a76e7ade81b5fb463b72126b to your computer and use it in GitHub Desktop.
def remove_duplicates(lista):
lista2 = []
for item in lista:
if item not in lista2: #is item in lista2 already?
lista2.append(item)
return lista2
print(remove_duplicates([1,2,3,3]))
@tnjman
Copy link

tnjman commented Jun 13, 2021

Very nice. I expanded on the idea; included "if else" logic & pre-populated "lista2"

def remove_duplicates(lista):
# -- Start of function
#   lista2 = [] <-- Orig had an empty "lista2"
    lista2 = [2,4,6] # <- Pre-populate lista2 for different behavior
    for item in lista:
        if item not in lista2: #is item in lista2 already?
            lista2.append(item)
        else: 
            print ("Item ", item, " already in lista2; item not added.")
    return lista2
# -- End of function
print("Here is the list, with unique values: ", remove_duplicates([1,2,3,3])) 

# Sample output:
# C:\scripts>py removedup.py
# Item  2  already in lista2; item not added.
# Item  3  already in lista2; item not added.
# Here is the list, with unique values: [2, 4, 6, 1, 3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment