Reputation: 31
I had tried to make a list free of duplicates from another defined list using list comprehension as follows,
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list = []
my_list = [x for x in num if x not in my_list]
Upon calling my_list
, I get back the same array
[1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
Could anyone kindly explain why this is happening?
Upvotes: 3
Views: 67
Reputation: 20689
You can try this list comprehension.
my_list=[]
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list=[my_list.append(x) or x for x in num if x not in my_list]
# [1,2,3,4,5]
If you don't care about the order.
my_lst=list(set(num))
From Python3.6 and above dictionaries store the insertion order or use collections.OrderedDict
. So, you can try this.
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list=list(dict.fromkeys(num).keys())
You can use seen
set to keep track of the elements that are seen. If an element in in seen
don't add it to my_list
.
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
seen=set()
my_list=[]
for x in num:
if x not in seen:
seen.add(x)
my_list.append(x)
my_list
# [1,2,3,4,5]
Upvotes: 2
Reputation: 656
my_list
isn't updated until after the comprehension is complete. During the comprehension my_list
is an empty list.
If order matters the approach you want to take is:
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list = []
check_set = set()
for x in num:
if x not in check_set:
my_list.append(x)
check_set.add(x)
If order does not matter:
my_list = list(set(num))
Upvotes: 3
Reputation: 1415
Using set is more feasible than an if condition along with for loop:
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list = list(set(num))
print(my_list)
Ouput:
[1, 2, 3, 4, 5]
Upvotes: 3
Reputation: 3780
you should try something like this :
In [99]: num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
...: my_list = []
In [100]: [my_list.append(item) for item in num if item not in my_list]
Out[100]: [None, None, None, None, None]
In [101]: my_list
Out[101]: [1, 2, 3, 4, 5]
The list is updated after the list comprehension process is complete because which the duplicates are still present.
Upvotes: 2