Reputation: 5
I just want simple list which remove duplicate digit
a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
m = []
def single_digit_list(a):
return [m.append(x) for x in a if x not in m]
print "New List", single_digit_list(a)
I was expected that new list gave me the one digit in list not repeated but i got following output
New List [None, None, None, None, None, None, None, None, None]
I can't understand what going on
Simple Know what is wrong in code
Upvotes: 0
Views: 160
Reputation: 16940
The reason why you got list of None
value is :
expression
given inside the list comprehension.Eg: [ expression for item in list if conditional ]
So, in your case you are appending an item into a list, which return None after appending the item if it was appending successfully.
Eg:
>>> ls = []
>>> print ls.append('a')
None
>>>
So, at the end of your list comprehension, your list m
got the correct unique element list but you return the list generate by the comprehension which is a list of None
value.
Conclusion:
You can fix that by return the value of m
not the result of list comprehension.
Or here is another easy solution using dictionary key:
>>> a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
>>> dict.fromkeys(a).keys()
[0, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
Upvotes: 0
Reputation: 4318
use set to remove duplicates:
m=set(a)
If you wanted output to be list:
m=list(set(a) )
Your code is good..You just have to return m...instead of returning return value of append...For ex, print m.append(10)
will print None
which is actually append's return value,you are not printing m.
You could modify you code as follows to return list:
a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
def single_digit_list(a):
m = []
[m.append(x) for x in a if x not in m]
return m #you have appended elements to m
Upvotes: 3
Reputation: 1905
If your list is already grouped, you can use groupby.
>>> x = [1, 1, 4, 4, 4, 5, 2, 2, 2, 3, 3]
>>> from itertools import groupby
>>> print [i[0] for i in groupby(x)]
[1, 4, 5, 2, 3]
This solution does not break order of element instead of converting to set.
Upvotes: 1
Reputation: 32189
You are trying to return a list of lists where all the lists are None.
This is because m.append()
does not return anything and you are trying to create a list of what m.append
returns
Just do it as:
def single_digit_list(a):
m = []
for x in a:
if x not in m:
m.append(x)
return m
>>> print single_digit_list([2,3,4,4,4,4,5,6,7,8,9,9,9,9,0])
[2,3,4,5,6,7,8,9,0]
Upvotes: 2