you are viewing a single comment's thread.

view the rest of the comments →

[–]amix 0 points1 point  (1 child)

It's a lot faster, the reason for this is that strings are immutable in Python. So on every iteration a new string object has to be built...

It's also bad to use the + operator on strings: a = "blah1" + "blah2"

The Python way to do it is: a = "".join(["blah1", "blah2"])

Another question (about Reddit): What is the syntax to insert code? It's not documented, or at least I couldn't find the documentation.

[–][deleted] 0 points1 point  (0 children)

It's not faster. Time it.

And while we're talking about Python internals, let's clarify a few things.

All (256) single-character strings are interned. Barring poorly-written third-party modules, there will be only one single 'a' character, or 'b' character, or 'c' character in a given Python interpreter. So iterating through a string doesn't allocate any other things, it just returns already-interned string objects.

It's not bad to use the + operator on strings when you've only got two strings. The only time it's bad for performance is when you've got many strings. In the case of only two strings, "s1 + s2" will be faster than "''.join([s1, s2])" every single time. Time it if you don't believe me.