Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove None when iterating through a list in python

I have this two unequal lists and i'm using itertools to loop through them and i'm trying to use the filter function to remove the None generated in List1 so that at the end of the day a contains only two elements instead of three (counting the none) but i keep getting this error: Type error: NoneType object is not iterable

import itertools

List1  = [['a'],['b']]
List2 = ['A','b','C']

l = list(itertools.chain(*List1))
print(l)

for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
    filter(None, a)
    print(a,b)
like image 849
danidee Avatar asked Jun 23 '26 11:06

danidee


1 Answers

Not entirely clear what you want. As I understand the question and the comments, you want to use izip_longest to combine the lists, but without any None elements in the result.

This will filter the None from the zipped 'slices' of the lists and print only the non-None values. But note that this way you can not be sure whether, e.g., the first element in the non_none list came from the first list or the second or third.

a = ["1", "2"]
b = ["a", "b", "c", "d"]
c = ["x", "y", "z"]

for zipped in izip_longest(a, b, c):
    non_none = filter(None, zipped)
    print non_none

Output:

('1', 'a', 'x')
('2', 'b', 'y')
('c', 'z')
('d',)

BTW, what your filter(None, a) does: It filters the None values from your a, i.e. from the strings "a" and "b" (which does not do much, as they contain no None values), until it fails for the last value, as None is not iterable. Also, it discards the result anyway, as you do not bind it to a variable. filter does not alter the original list, but returns a filtered copy!

like image 134
tobias_k Avatar answered Jun 26 '26 00:06

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!