You get TypeError
because you try to sum
lists. Let me change your code a little bit:
In[1]: arr = [1, 2, 3, 4, 5]
[sorted(arr)[1:-1] for x in range(len(arr))]
Out[1]: [[2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4]]
I change your generator expression on list comprehension to show the idea. Really you generate a list on each implicit next
call. A further consequence of this error is:
In[2]: sum([[1],[2],[3]]) # will raise TypeError
Out[2]: TypeError: unsupported operand type(s) for +: 'int' and 'list'
In[3]: sum([[1],[2],[3]], []) # if you specify start, it will work
Out[3]: [1, 2, 3]
The signature of sum
function is sum(iterable[, start])
. Sums start and the items of an iterable from left to right and returns the total. start
defaults to 0. The iterable‘s items are normally numbers, and the start value is not allowed to be a string. In fist case you really try to sum [1] + [2] + [3] + 0
, and because +
between list
and int
is not defined, that's why you get TypeError. In the second case [1] + [2] + [3] + []
this operation concatenates list and is perfectly valid.
And if you want review of your code and some feedback look at Stackexchange's CodeReview site.
You can try this, if you like one-liners. Here is also an assumption that a valid array is always instance of <class list>
:
In[4]: sum_array = lambda arr: sum(sorted(arr)[1:-1]) if isinstance(arr, list) else 0
sum_array([4, 3, 8, 1, 7, 12, 5, 9])
Out[4]: 36
But it's not good practice!
None
by equality; use identity. - jonrsharpefor x in range(len(arr or [])-2)
- Moses Koledoyearr
beingNone
is just a distraction. Assume thatarr
is at least a valid list of things you can add, and go from there. You aren't checking thatarr
doesn't contain strings, after all. - chepner