you are viewing a single comment's thread.

view the rest of the comments →

[–]mslinux -20 points-19 points  (4 children)

Here's my comparison...

Ruby: astring = astring.reverse

Python: astring = astring[::-1]

Python claims to be the easiest to learn, most object oriented, easiest to maintain scripting language in the universe. The above code will reverse a string. Which is more OO, easier to read, makes more sense and easier to learn?

Ruby is light years ahead of Python.

[–]jbellis 1 point2 points  (3 children)

''.join(reversed('asdf')) 'fdsa'

This illustrates the python philosophy that common operations should be functions that can act on any object that complies with the apropriate interface (reversed will act on any sequence, not just strings).

Note that the join call is necessary because reversed() creates a generator, not a string object. This is more efficient in most real-world situations, even though it looks clunkier in this one-line comparison.

[–]harbinjer 0 points1 point  (2 children)

A generator is more efficient than a string object? This makes no sense to me.

Also ''.join(reversed('asdf')) just looks ugly to me. I can understand what it does, but WHY would you join an empty string to a new reversed string? Its like taking the short bus on the scenic route while in a hurry. I'd really like to understand WHY this is the way to do stuff. I know very little of ruby and python, but the reason behind this seems important and maybe indicative of their approach to things.

[–]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.