0

guys i'm trying to do this program where i have to take a list and separate all the non unique elements and put it in a list without the changing the order of it. for example
[1,2,3,1,3]=[1,3,1,3]
[5,5,5,5]=[5,5,5,5]
[1,2,3,4,5]=[]

So for this, I did the program in python and put some flags to help me know where i'm doing wrong.So in the program i tried to reset the list3 value( after deleting an element of it inside a loop and exiting it) but it wouldn't let me do it.so any help would be greatly appreciated. Thank you guys very much.

list1=[1,2,3,1,3]
list2=[]
d=0
m=0
l=len(list1)
print(l)
for x in range(0,l):
    print('for loop')
    list3=list1  # I used this to reset the list3 to list1 and use it in the loop but it wouldn't reset
    print('this is the reset of list 3',list3)
    m=list1[x]
    print(m,x)
    print(list3[x])
    del (list3[x])

    while True:
        print('while loop',list3[d])

        if m==list3[d]:
            print('its here')
            list2.append(m)
            print('this is list2: ',list2)
        d+=1

        if d==lenght(list3)-1:
            print('its here22222')
            break
print(list2)

# my results were

5
for loop
this is the reset of list 3 [1, 2, 3, 1, 3]
1 0
1
while loop 2
while loop 3
while loop 1
its here
this is list2:  [1]
its here22222
for loop
this is the reset of list 3 [2, 3, 1, 3]
3 1
IndexError: list index out of range
vineeth
  • 114
  • 1
  • 14
  • 1
    list3= list1 is not copying list1, see http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python – paisanco May 08 '16 at 03:17

1 Answers1

0

Does this do what you want?

#list1=[5,5,5,5,5]
list1=[1,2,3,1,3]
#list1=[1,2,3,4,5]
list2=[]

for num in list1:
    if list1.count(num) > 1:
        list2.append(num)

print(list2)
davo36
  • 694
  • 9
  • 19
  • it does work. i know the count function. i used it too. but i just don't get why the list3 in the 9th line doesn't reset the list3 to list1. Thanks a lot @dovo36. :) – vineeth May 08 '16 at 03:26
  • Oh, ok. It's as paisonco said above. list3=list1 makes list3 point to the same memory as list1. So then they are 2 different labels for the same thing. If you want to copy list1, overwriting list3, then read that link he gave you, it shows the different ways that can be done. – davo36 May 08 '16 at 03:31
  • thanks a lot @davo36. that really helped me out – vineeth May 08 '16 at 03:35