0

I have a list whose elements are either a json object or None. What would be the most elegant way to convert it into a list of 0's and 1's. For example here is my input :

mylist = [j1, j2, None, j3, None]

j1, j2, j3 are json objects. The expected output is

output_list = [1, 1, 0, 1, 0]

I can implement this using a for loop followed by if statement. Is there a way to do it which is more elegant/pythonic?

Santanu C
  • 1,240
  • 2
  • 18
  • 35

2 Answers2

5

You can use a list comprehension and a conditional expression:

mylist[:] = [0 if x is None else 1 for x in mylist]

See a demonstration below:

>>> mylist = ['a', 'b', None, 'c', None]
>>> mylist[:] = [0 if x is None else 1 for x in mylist]
>>> mylist
[1, 1, 0, 1, 0]
>>>

The [:] will make it so that the list object is kept the same:

>>> mylist = ['a', 'b', None, 'c', None]
>>> id(mylist)
34321512
>>> mylist[:] = [0 if x is None else 1 for x in mylist]
>>> id(mylist)
34321512
>>>
Community
  • 1
  • 1
  • Great answer. Perhaps even: `mylist[:] = [0 if x else 1 for x in mylist]` if you are interested in the general truthiness as opposed to only `None`. – s16h May 11 '14 at 23:38
1

You can also use map function on your list, here's a python shell's session:

>>> l = ['j1', 'j2', None, 'j3', None]
>>> map(lambda e : e is None, l)
[False, False, True, False, True]
>>> map(lambda e : e is not None, l)
[True, True, False, True, False]
>>> map(lambda e : int(e is not None), l)
[1, 1, 0, 1, 0]
Aif
  • 10,331
  • 1
  • 27
  • 41