Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace None value in list?

I have:

d = [1,'q','3', None, 'temp'] 

I want to replace None value to 'None' or any string

expected effect:

d = [1,'q','3', 'None', 'temp'] 

a try replace in string and for loop but I get error:

TypeError: expected a character buffer object 
like image 241
user7172 Avatar asked Oct 14 '13 15:10

user7172


People also ask

How do I change none values in a list?

Use a list comprehension to replace None values in a list in Python, e.g. new_list_1 = ['' if i is None else i for i in my_list] . The list comprehension should return a different value, e.g. an empty string or 0 if the list item is None , otherwise it should return the list item.

How do I remove none from a list?

The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.

Can you replace values in a list?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

Can none be in a list Python?

None is a valid element, but you can treat it like a stub or placeholder. So it counts as an element inside the list even if there is only a None .


Video Answer


1 Answers

Use a simple list comprehension:

['None' if v is None else v for v in d] 

Demo:

>>> d = [1,'q','3', None, 'temp'] >>> ['None' if v is None else v for v in d] [1, 'q', '3', 'None', 'temp'] 

Note the is None test to match the None singleton.

like image 168
Martijn Pieters Avatar answered Oct 06 '22 07:10

Martijn Pieters