1

I want to create a list from an existing list after removing all duplicates. Program works if I use a "for loop" but nothing happens if I use a list comprehension.

#use for loop
l=[1,2,2,3,1,1,2]
j=[]

for i in l:
    if i not in j:
        j.append(i)

print l
print j


#using list
l1=[1,2,2,3,1,1,2]
j1=[]

j1=[i for i in l1 if i not in j1]

print l1 
print j1
Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
Voneone
  • 129
  • 6

2 Answers2

2

The expression [i for i in l1 if i not in j1] is evaluated and then assigned to j1. So during the evaluation j1 stays empty.

BTW: An easy was of removing duplicates is to pass the list to the set function and then to the list function if you need a list:

j1=list(set(l1))
Reto Aebersold
  • 16,306
  • 5
  • 55
  • 74
0

j1 is [] at the start and isn't updated at intermediate points within the list comprehension. Could do this instead of list comprehension though:

l1=[1,2,2,3,1,1,2]
j1=list(set(l1))

print l1 
print j1
Brian
  • 1,988
  • 1
  • 14
  • 29