[['user_1',
'user_2',
'user_8',
None,
None],
['ben',
'karl',
None,
None]]
I try to remove the missing values
for element in df:
element=[x for x in element if x is not None]
this code leave everything as it was
[['user_1',
'user_2',
'user_8',
None,
None],
['ben',
'karl',
None,
None]]
I try to remove the missing values
for element in df:
element=[x for x in element if x is not None]
this code leave everything as it was
my_list= [['user_1',
'user_2',
'user_8',
None,
None],
['ben',
'karl',
None,
None]]
print [ [ elt for elt in a_list if elt is not None ] for a_list in my_list ]
[['user_1', 'user_2', 'user_8'], ['ben', 'karl']]
The problem with your code is that the line
element=[x for x in element if x is not None]
creates the new filtered list and binds it to the name element, which replaces the old list object that the name element was bound to. But we can use slice assignment to make it mutate that list instead:
df = [
[
'user_1',
'user_2',
'user_8',
None,
None,
],
[
'ben',
'karl',
None,
None,
]
]
# Remove the `None` values
for element in df:
element[:] = [x for x in element if x is not None]
for row in df:
print(row)
output
['user_1', 'user_2', 'user_8']
['ben', 'karl']
Reassigning element does not alter the list, because element is a separate variable.
With a small change, you can generate a new outer list using a nested comprehension, something like this:
df = [[x for x in element if x is not None] for element in df]