Python Forum

Full Version: how to take out duplicates from a list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello! So my teacher wants up to take out duplicates from a list that the user puts. This is my code:

num=int(input("First List- How many elements do you want?: "))
lista=list()
for i in range(num):
    element=int(input("   Input a number: "))
    lista.append(element)

num=int(input("Second List- How many elements do you want?: "))
listb=list()
for i in range(num):
    element=int(input("   Input a number: "))
    listb.append(element)

print "This is your new list: "
listc=list()
listc=lista+listb
listc.sort()
print listc
So basically, if listc's output is
Output:
[2,2,3,5,5,8,9]
because the user may have put the same numbers twice, then we need to take out the duplicates so it then becomes this instead.
Output:
[2,3,5,8,9]


My teacher gave us this but I don't quite understand it, or how to even incorporate it into my code, and if anything I might not:
new=lista
for i in listc:
    m=listc[0]
    if m not in new:
        new.append(m)
Anyways, thank you if anyone answers, I appreciate it. Blush
The simplest way.
>>> lst = [2,2,3,5,5,8,9]
>>> set(lst)
{2, 3, 5, 8, 9}
(Mar-08-2019, 01:55 PM)helpme Wrote: [ -> ]My teacher gave us this but I don't quite understand it, or how to even incorporate it into my code, and if anything I might not:
new=lista
for i in listc:
    m=listc[0]
    if m not in new:
        new.append(m)
It's written in a confusing and not so good way can you tell your teacher Wink
See if this is better to understand.
>>> lst = [2,2,3,5,5,8,9]
>>> unique = []
>>> for ele in lst:
...     if ele not in unique:
...         unique.append(ele)
...         
>>> unique
[2, 3, 5, 8, 9]
Yeah, I don't understand that either. If you were looking to combine lista and listc without duplicates, it would be:

new=lista[:]
for i in listc:
    if i not in new:
        new.append(m)
So you loop through listc, and if it's not already in new, you add it to new. Note the [:] on the first line. That makes new a copy of lista, rather than just a reference to the same point in memory. Without that, any modifications to new also get made to lista. If you want lista to stay the same you need that. If you are fine with modifying lista, why make a new variable named 'new'?