2

I have list:

test_list = ['one','two',None]

Is there any simple way to replace None with 'None' ,without using index, because index for None maybe different each time.

I tried :

conv = lambda i : i or 'None'
res = [conv(i) for i in test_list] 

It works ,is there another way to do so ?

2
  • 2
    "It works ,is there another way to do so ?" What precisely about the way you are doing it now is not adequate? Perhaps just drop the pointless conv = lambda i : i or 'None' and use that expression in the list comprehension? Commented Nov 8, 2022 at 21:01
  • i or 'None' can be too broad. It will turn more than just None into a string. '' and 0 would also be converted to string 'None'. Commented Nov 8, 2022 at 21:13

2 Answers 2

4

In this way all the data types would be converted to string

test_list = ['one','two',None]    
res = [str(i) for i in test_list]

In this the data type will also be preserved

res = ['None' if i is None else i for i in test_list]
Sign up to request clarification or add additional context in comments.

Comments

-1

Another way:

test_list = ['one', 'two', None]    
res = [i or 'None' for i in test_list]

Even better if you're working with numbers, since int(None) gives an error:

test_list = [1, 2, None]    
res = [i or 0 for i in test_list]

5 Comments

This will convert ['one', ''] to ['one', 'None'], or to ['one', 0], respectively, which is probably not desired.
I just realized this is actually what the OP was initially using, so I think it is what he desired
Also, I forgot to say... ['one', 0] can't happen, since I said you'll use [i or 0 for i in test_list] only if you will use actual numbers, not strings
That last comment is not clear from your answer. You wrote "if you're working with numbers", not "if you're working with ONLY numbers" or "if you don't use strings". Besides, this does not replace None with 'None', which is the question. So this answer is just wrong.
Sure, if you're working with only* numbers, then 😒. Also, I know this is not related to the original answer, it's just an addition as something interesting, the main part of the answer is in the first lines of the answer, where I say "Another way"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.