extend two lists and take median in one line

Viewed 38

I'm trying to take the median of two concatenated lists, where one of the lists is the result of the numpy repeat function.

This code works fine:

from numpy import median, repeat
g = [4, 5, 6]
g.extend([i.item() for i in repeat(0, 10)])
median(g)

For some reason the above code fails if I try to do this in one line:

g = [4, 5, 6]
median(g.extend([i.item() for i in repeat(0, 10)]))
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

I really need to do this in one line. I tried using asarray but get the same error:

from numpy import asarray
g = [4, 5, 6]
median(asarray(g.extend([i.item() for i in repeat(0, 10)])))

Above, I use item() to convert the numpy type output of repeat back to regular python types.

1 Answers

Because g.extend() returns None, and not the extended list, you can use the + operator between lists instead:

>>> median(g + ([i.item() for i in repeat(0, 10)]))
0.0
# or, getting rid of the unnecessary list comprehension as per @xdhmoore's comment:
>>> median(g + repeat(0, 10).tolist())

Adding two lists together with + functionally does the same as .extend(), but not in place:

>>> g + ([i.item() for i in repeat(0, 10)])
[4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


# vs:

>>> g = [4, 5, 6]

>>> g.extend([i.item() for i in repeat(0, 10)])

>>> g
[4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Related