Reverse


#1

This code works. I’m asking for an opinion. Is this an odd approach to this challenge?



def reverse(text):
    rev_text = []
    for i in text:
        rev_text.insert(0, i)
    return ''.join(rev_text)



Reverse - Naive solution?
#2

Hi @bjt302,

You used an interesting approach that raises interesting issues about Python lists.

There are a variety of Python implementations, and they may differ in the details regarding how they implement list methods internally. When you insert an item at index 0, the indexes of all the items already in the list must be shifted in order to accommodate the new item. This could be a source of inefficiency, especially in a loop, where such an operation is performed repeatedly. However it is possible that some implementations of Python optimize the insert method in various ways.

To be safe, a more efficient approach would be to iterate through text in reverse order, and append each character to rev_text. Then, the indexes would not need to be shifted. See the following …

    for i in range(len(text) - 1, -1, -1):
        rev_text.append(text[i])

For this exercise, many users initialize an empty str and concatenate each character onto it. However that also introduces inefficiency, because str objects are immutable, meaning they cannot be altered. Whenever str objects are concatenated, Python creates a new str. In a loop, this happens repeatedly. Via the use a list on which to append the characters, and a final join after the loop, repeated concatenation can be avoided.

While efficiency is not so important when processing a small str, it is good to keep efficiency in mind, and to practice it in general, in preparation for cases where you might handle large amounts of data.


#3

That makes sense. Thanks for the rapid response!


#4