I have a list which has elements of type int and str. I need to copy the int elements to another list. I tried a list comprehension which is not working. My equivalent loop is working.
input = ['a',1,'b','c',2,3,'c','d']
output = []
[output.append(a) for a in input if type(a) == int]
[None, None, None]
same logic in loop works.
output = []
for a in input:
if type(a) == int:
output.append(a)
print(output)
[1,2,3,]
Can I know what made the difference.
5 Answers 5
When you're doing:
input = ['a',1,'b','c',2,3,'c','d']
output = []
[output.append(a) for a in input if type(a) == int]
append returns None, so that's why lot of none's
Btw,:
print(output)
Will be desired result.
Your logic actually works!
But it's not good to use list comprehension as side-effects, so best way would be:
output=[a for a in input if type(a) == int]
Also final best would be isinstance:
output=[a for a in input if isinstance(a,int)]
Comments
An idiomatic solution would be:
input = ['a', 1, 'b', 'c', 2, 3, 'c', 'd']
output = [a for a in input if type(a) == int]
You do not want to use output.append. That is implied by the list comprehension. You can change the first a in the comprehension to an expression containing a. output.append(a) is a method call that returns NONE
Use list comprehensions when you want to collect values into a list you are assigning to a variable or as part of larger expression. Do not use them for side effects as a different format for a 'for loop'. Instead use the for loop.
Spaces after the commas are not required but are considered good style.
Comments
input = ['a',1,'b','c',2,3,'c','d']
output = [a for a in input if type(a) == int]
The list comprehension automatically creates the list - no need to use append()
Comments
You can use the following solution to solve your problem:
output = [a for a in input if type(a) == int]
Comments
A solution would be:
input = ['a',1,'b','c',2,3,'c','d']
output=[item for item in input if type(item) is int] or
output=[item for item in input if isinstance(item,int)]
and the last one is quicker than the first.
but when you use:
input = ['a',1,'b','c',2,3,'c','d']
output=[]
[output.append(a) for a in input if type(a) == int]
it means the code execute two results ,the one is output.append(a) append object in end and the list comprehension with if condition creates a new list object after executing ,as a.append()(Look_in_IDLE) return None , so there are three None.
print(output)at the end.