I have this python code, I want to convert the NoneType variable into a string, so I wrote this condition to catch it, but i'm unable to overwrite it. How can that be done ? Thanks
int_list= ['10','3',None,'5','8']
i = 0
for l in int_list:
if l is None:
l == 'hello'
print l
i+=1
Expected Output:
10
3
hello
5
8
You are just changing the value of a variable l
, currently containing an element in int_list
, not the list itself.
You need to reassign the element in the list with a new value, using the index
(here, i
) to access this element in the list object.
Do this:
int_list= ['10','3',None,'5','8']
i = 0
for i in range(len(int_list)):
if int_list[i] is None:
int_list[i] = 'hello' # accessing element IN THE LIST as index/position i, reassigning it to the new value 'hello'
i+=1
print(int_list)
Output:
['10', '3', 'hello', '5', '8']