6

I'm confused as to how the insert() function in Python works. I was trying to reverse a string and I thought I could do that by simply creating a list which stores the characters of the original string in reverse order. Here's my code:-

def reverse(text):
    rev = []
    l = len(text) - 1
    for c in text:
        rev.insert(l, c)
        l -= 1
    return rev

print reverse("Hello")

Yet the output I get is ['o', 'H', 'l', 'e', 'l'], which is obviously wrong. Any help would be appreciated. Is there something wrong in the logic I've applied?

7 Answers 7

6

yes, you can use insert() on an empty list in python. that leads directly to the problem with your code:

rev = []
rev.insert(3, 'a')  # ['a']

if the index is bigger than the length of your list, the item will just be appended. in your code the first insert is 'H' at position 5; but this will just result in rev = ['H']. this is the wrong position for 'H'!

a remedy would just be to insert at position 0:

def reverse(text):
    rev = []
    for c in text:
        rev.insert(0, c)
    return rev

(just in case: the simplest way to do that in python is: 'Hello'[::-1].

Sign up to request clarification or add additional context in comments.

Comments

3

To insert at the start of a list (empty or not), the first argument to insert() must be 0.

Minimal Code Example

l = [*'Hello']

rev = []
for c in l:
     rev.insert(0, c)

rev
# ['o', 'l', 'l', 'e', 'H']

Comments

2

While other's have showed you how to fix your method, I'll explain what was wrong with your previous one.

The problem with your approach is that your list changes each iteration. So the insertion positions of your elements are relative to the current length of the list. Here is a step through of what you for loop is basically doing:

>>> rev = []
>>> l = len('Hello') - 1
>>> l
4
>>> # first iteration
>>> rev.insert(l, 'H')
>>> rev
['H']
>>> l -= 1
>>> l
3
>>> # second iteration
>>> rev.insert(l, 'e')
>>> rev
['H', 'e']
>>> l -= 1
>>> l
2
>>> # third iteration
>>> rev.insert(l, 'l')
>>> rev
['H', 'e', 'l']
>>> l -= 1
>>> l
1
>>> # fourth iteration
>>> rev.insert(l, 'l')
>>> rev
['H', 'l', 'e', 'l']
>>> l -= 1
>>> l
0
>>> # Fifth iteration
>>> rev.insert(l, 'o')
>>> rev
['o', 'H', 'l', 'e', 'l']
>>> l -= 1
>>> l
-1
>>> # end

As you can see, your insertions position changes based on how the list grows. Sometimes insert behaves like append(), other times it goes back to behaving like insert().

You can fix this problem by making your insertion position 0. That way, you always append to the beginning of the list regardless of how the list changes:

rev.insert(0, c)

Comments

1

What you are looking for is a deque:

from collections import deque

s = "Hello"

d = deque() #create a deque object

for i in s:
   d.appendleft(i)


print(''.join(d))

Output:

olleH

A deque gives you the option of creating a list mutable at both ends. The method appendleft() is the same as insert(0, value).

Comments

1

In python, lists are zero-indexed. So when you do insert(1,c), you are actually inserting in the SECOND position in the list. To insert at the beginning of the list, use insert(0,c).

2 Comments

append will always add the element at the end of the list. Since I want to reverse my string, I actually want to go in the other direction, from the final index to the 0th.
That's where the [::-1] (reversed list) comes in handy. Looping through the inversed list will get the desired output with insert(0,c) or append().
0

You can try this way:

def reverse(text):
  rev = []
  for c in text:
    rev.insert(0, c)
  return rev

print reverse("Hello")

Comments

-1
def reverse(text):
  revText = text[::-1]
  return list(revText)

print reverse("Hello")

result

['o', 'l', 'l', 'e', 'H']

1 Comment

An alternative implementation is Ok, but it doesn't answer the question "How to use insert()?`"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.