Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use insert() on an empty list in Python?

Tags:

python

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?

like image 667
Vaibhav Avatar asked Jul 13 '17 15:07

Vaibhav


2 Answers

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

like image 131
hiro protagonist Avatar answered Sep 29 '22 18:09

hiro protagonist


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']
like image 29
cs95 Avatar answered Sep 29 '22 18:09

cs95