3

a = [None, None, '2014-04-27 17:31:17', None, None]

trying to replace None with ''

tried many times, this the closest I got. b= ['' for x in a if x==None] which gives me four '' but leaves out the date

i thought it would be b= ['' for x in a if x==None else x] but doesn't work.

what if it is nested like so:

a = [[None, None, '2014-04-27 17:31:17', None, None],[None, None, '2014-04-27 17:31:17', None, None],[None, None, '2014-04-27 17:31:17', None, None]]

Can you still use list comprehensions?

jason
  • 3,811
  • 18
  • 92
  • 147
  • When you compare something with `None` use `is` operator ([description](http://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or)) – mblw Apr 27 '14 at 10:03
  • `None` and `''` are two very different things; be sure it doesn't have an impact somewhere else. – Burhan Khalid Apr 27 '14 at 10:11
  • yeah, reading from google sheets blank become `None`, but to put them back to the same position you have change `None` back to `''`, or else it will be a page of `None`s – jason Apr 27 '14 at 10:13

4 Answers4

10

Just modify your code as follows:

b = ['' if x is None else x for x in a]    #and use is None instead of == None

>>> print b
['', '', '2014-04-27 17:31:17', '', '']

Explanation

For nested lists, you can do:

b = [['' if x is None else x for x in c] for c in a]
Community
  • 1
  • 1
sshashank124
  • 31,495
  • 9
  • 67
  • 76
5

You don't even have to use a comprehension:

a = map(lambda x: '' if x == None else x, a)

vinit_ivar
  • 610
  • 6
  • 16
4

You can use the or operator for this:

>>> a = [None, None, '2014-04-27 17:31:17', None, None]
>>> print [x or "" for x in a]
['', '', '2014-04-27 17:31:17', '', '']

..because the or operator works like so:

>>> None or ""
''
>>> "blah" or ""
'blah'

..although this might not be ideal, as it will replace any False'ish values, e.g:

>>> 0 or ""
''

If this is a problem in your case, the more explicit ['' if x is None else x for x in a] mentioned in sshashank124's answer which will only replace None specifically

dbr
  • 165,801
  • 69
  • 278
  • 343
2

You can use a comprehension if you know in advance how deep the list is nested (although it wouldn't be particularly readable), for arbitrary nested lists you can use a simple "recursive map" function like this:

def maprec(obj, fun):
    if isinstance(obj, list):
        return [maprec(x, fun) for x in obj]
    return fun(obj)

Usage:

new_list = maprec(nested_list, lambda x: '' if x is None else x)
gog
  • 10,367
  • 2
  • 24
  • 38