4 ms·
Then what would you have [1,2,'q',[1,('a',2)]] + 4 yield? The reason why numpy lets you do math operation on each element in an array is because you can
by wodenokoto 12y ago
Then what would you have
[1,2,'q',[1,('a',2)]] + 4
yield? The reason why numpy lets you do math operation on each element in an array is because you can safely assume that each element is a number. You can assume absolutely nothing about the types of the elements in a list.
- Animats 12y ago"TypeError: cannot add 'str' and 'int' objects." Just because you can define semantics for nonsense doesn't mean you should.
- ubernostrum 12y agoYou apparently want lst * intval to be equivalent to map(lambda n: n * intval for n in lst) or [n * intval for n in lst]. Since Python has a convenient built-in and even syntactic sugar for doing what you want, why not let the operator overloading handle a different case? (also, your issue is not with "nonsense semantics", it's with "my idea of how this operator should've been overloaded is different from their idea", and perhaps is even a beef with the idea of operator overloading in general, though if you like numpy I think you wouldn't like losing operator overloading)
- dalke 12y agoI'll modify the example slightly to something which doesn't have a type error: [1,2,'q',[1,('a',2)]] * 4 With element-by-element operations, that would be [1 * 4,2 * 4,'q' * 4,[1,('a',2)] * 4] giving [4, 8, 'qqqq', [1 * 4, ('a', 2) * 4]] applying that again, assuming that tuple * scalar is also applied element-wise gives: [4, 8, 'qqqq', [4, ('a' * 4, 2 * 4)]] and ends up with [4, 8, 'qqqq', [4, ('aaaa', 8)]] I can't think of any case where that's meaningful. Also, what should this do: x = [1] x.append(x) print(x + x) print(x * 4) ? Currently these print: [1, [1, [...]], 1, [1, [...]]] [1, [1, [...]], 1, [1, [...]], 1, [1, [...]], 1, [1, [...]]] because the print function knows how to handle recursive definitions. Do all of the element-wise operations need to handle cyclical cases like this? I think numpy can get away with not worrying about this precisely because, as wodenokoto pointed out, it can assume a flat structure.