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?
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]
.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With