Reputation: 323
I have a list that looks like this:
[None, None, None, None, [(u'data1', 2.0, 2.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, [(u'data2', 8.0, 5.0, 0.625, 1.25, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, [(u'data3', 1.0, 1.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, None, None, None, None, None, None, None]
I need to remove the None's so i can iterate through the list. Should I not insert if the value is None, or just remove them from the list after they are inserted?
I am building the list like this:
item = (val1, val2, val3, val4, val5, start_date, end_date)
array.append(item)
The first 5 values are the ones that will return None. But looking at the data, sometimes it only inserts 4 None's, sometimes 5.
I have tried several solutions from stack, such as:
[x for x in result is not None]
and
if val is not None:
item = (val1, val2, val3, val4, val5, start_date, end_date)
array.append(item)
but for some reason, it will still append even if the val is None.
Upvotes: 0
Views: 1554
Reputation: 9869
You need to fix your list comprehension.
results = [None, None, None, None, [(u'data1', 2.0, 2.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, [(u'data2', 8.0, 5.0, 0.625, 1.25, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, [(u'data3', 1.0, 1.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, None, None, None, None, None, None, None]
results = [result for result in results if result is not None]
>>> [[(u'data1', 2.0, 2.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], [(u'data2', 8.0, 5.0, 0.625, 1.25, '2015-10-01', '2015-10-01')], [(u'data3', 1.0, 1.0, 1.0, 1.0, '2015-10-01', '2015-10-01')]]
Upvotes: 2
Reputation: 5830
you are missing a piece of your list comprehension
[x for x in result if x is not None]
Upvotes: 3