0

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
1
  • Do you really want to have a mixed list of integers and strings? Integers and None seems better, IMHO. Commented Jun 22, 2015 at 15:25

4 Answers 4

2

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] = ''
Sign up to request clarification or add additional context in comments.

Comments

2

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]]

Comments

1

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]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.