4 ms·
Using * on a sequence wouldn't get past code review with me, it's an obscure feature with surprising side-effects and it doesn't explain your thinking. Only co
by EdwardDiego 3y ago
Using * on a sequence wouldn't get past code review with me, it's an obscure feature with surprising side-effects and it doesn't explain your thinking.
Only context I've ever found it useful in, is if you're unit testing something that accepts a string of max length M, then
bad_str = "A" * (M + 1)
Is quite nice and also, easy to interpret.
But if you're calling multiply on a list[list[Any]] lol nah mate, what the hell are you playing at, make a for loop and add comments.
- thomasahle 3y agoThere's always the `zip(*[iter(x)]*2)` to split an iterable into even/odds.
- maweki 3y ago> Using * on a sequence wouldn't get past code review On a mutable sequence. Or anything mutable. [] being a sequence is not the issue here. If you work with immutable stuff, * is really not an issue.
- boxed 3y agoIt's not great though. I do use it to repeat strings but it should have been a method and not weirdly overloading *. This type of misuse of operator overloading is why people from a C++ background think operator overloading is evil. In python it's mostly ok, due to a more restrained culture, but this is a good example of when it's bad.
- maweki 3y agoIt's not weirdly overloaded. 'a'*3 == 'a'+'a'+'a'
- ponco 3y agoI feel like far too much attention is given to `[[]] * n`. In the grand scheme of things, no serious python programmer is using multiply on a sequence outside of the string construction convenience. It's also remarkebly easy to diagnose once you see the unexpected behaviour, so anyone asking for help is going to be instantly told not to do it and use a comprehension instead. I'm sure there are plenty of other pitfalls in other languages, though I concede this one is especially unintuitive to a new person.