5 ms·
I'm surprised no one's mentioned a while loop yet: start = 0 while (end := my_str.find("x", start)) != -1: print(my_str[start:end]) sta
by quietbritishjim 4y ago
I'm surprised no one's mentioned a while loop yet:
start = 0
while (end := my_str.find("x", start)) != -1:
print(my_str[start:end])
start = end + 1
vs
start = 0
while True:
end = my_str.find("x", start)
if end == -1:
break
print(my_str[start:end])
start = end + 1
I'm still on the fence myself so I sympathise with your view, but the first version is certainly a bit tidier in this case.
- paulluuk 4y agoI never use the walrus operator but your second example is pretty typical and it does indeed look a lot cleaner with the walrus operator.
- Woden501 4y agoSure it's "tidier" if by that you mean smaller. Someone who doesn't work in Python all the time and isn't aware of these kinds of operators is going to have to spend a decent amount of time unpacking what the hell that all means whereas someone can take one look at the standard while loop, see the logic laid out plainly, understand what's happening, and make changes, if necessary, fairly easily. Unless there's a performance benefit to an operator like this I'll forgo "tidy" for clear any day of the week. Then again I'm just a senior dev whose only professional experience with Python was maintaining other people's Python projects who never had to touch them again after they wrote them, and who used Python for things Python should not have been used for just because it's "easy" to write.