-1

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
petezurich
  • 9,280
  • 9
  • 43
  • 57
alioua walid
  • 247
  • 3
  • 19
  • your "list" is actually a tuple so you won't be able to modify it in-place, if it was a list you would do something along the lines of `int_list[i] = 'hello'` since just reassigning the local variable `l` doesn't even attempt to modify the original list. – Tadhg McDonald-Jensen Feb 24 '20 at 22:14
  • If you search in your browser for "Python list tuple tutorial", you'll find references that can explain this much better than we can manage here. Your code does not attempt to change `int_list`. – Prune Feb 24 '20 at 22:15
  • @TadhgMcDonald-Jensen I tried with a list l = [], I want to assign a var type from that condition – alioua walid Feb 24 '20 at 22:16
  • Does this answer your question? [How to modify list entries during for loop?](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) – Tadhg McDonald-Jensen Feb 24 '20 at 22:21

2 Answers2

1

You're using the conditional test as an assignment. This will not work. Instead, try:

int_list= ['10','3',None,'5','8']
i = 0
for l in int_list:
    if l is None:
        l = 'hello'
    print l
    i+=1

In short, replace the == in your fifth with a single =. Hope that helps.

hd1
  • 33,938
  • 5
  • 80
  • 91
1

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']
Xhattam
  • 195
  • 1
  • 11