I would like to replace the Null value of None with a zero length string. My code seems to have no effect. What am I missing?
mylist = [[2,3,None],[None,3,4]]
for x in mylist:
for y in x:
if y is None:
y = ''
print mylist
I would like to replace the Null value of None with a zero length string. My code seems to have no effect. What am I missing?
mylist = [[2,3,None],[None,3,4]]
for x in mylist:
for y in x:
if y is None:
y = ''
print mylist
Unfortunately, all you're currently doing is setting the variable y to a completely different string '', which has absolutely no bearing on your original list, and the information is completely lost when you continue iteration. To fully replace all those, you could use an indexing for loop.
for i in range(len(mylist)):
for j in range(len(mylist[i])):
if mylist[i][j] == None:
mylist[i][j] = ''
You are doing it wrongly, when iterating over a list, you get the list element, trying to set it within the loop does not change it within the actual list, you need to get the index of that element and change it in the list , you can use enumerate function for that.
Example -
mylist = [[2,3,None],[None,3,4]]
for x in mylist:
for i,y in enumerate(x):
if y is None:
x[i] = ''
print mylist
>> [[2, 3, ''], ['', 3, 4]]
The variable y is only a temporary read access to the respective element of the list. If you would like to change the list values, try accessing them directly via a counter.
The code below reassembls the entire nested list, which is another alternative:
mylist = [[2,3,None],[None,3,4]]
mylist = [[yI if yI is not None else '' for yI in xI] for xI in mylist]
Personally I do not like mutating lists whilst iterating over them, returning a new list is what every function in the standard library does. Here is a function that will return a new list with the desired element replaced, it will work for lists of any "depth" for lack of a better word
def list_replace(old_list, replace=None, replace_with=''):
new_list = []
for elem in old_list:
if isinstance(elem, list):
new_list.append(list_replace(elem))
else:
new_list.append(replace_with if elem == replace else elem)
return new_list