Is it possible to use insert () in an empty list in Python?

I am confused about how a function works insert()in Python. I tried changing the string, and I thought I could do this by simply creating a list in which the characters of the original string are stored in reverse order. Here is 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")

But I get the conclusion ['o', 'H', 'l', 'e', 'l'], which is obviously wrong. Any help would be greatly appreciated. Is there something wrong with the logic I applied?

+4
source share
7 answers

To insert at the top of the list (empty or not), the first argument to insert()should be 0.

Minimum Code Example

l = [*'Hello']

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

rev
# ['o', 'l', 'l', 'e', 'H']
+1
source

, insert() python. :

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

, . 'H' 5; rev = ['H']. 'H'!

0:

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

( : python: 'Hello'[::-1].

+2

python . , insert(1,c), SECOND . , insert(0,c).

+1

, , deque:

from collections import deque

s = "Hello"

d = deque() #create a deque object

for i in s:
   d.appendleft(i)


print(''.join(d))

:

olleH

Deque , . appendleft() insert(0, value).

+1

, , , .

, . , . , :

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

, , . insert append(), insert().

, 0. , , :

rev.insert(0, c)
+1

:

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

print reverse("Hello")
0
source
def reverse(text):
  revText = text[::-1]
  return list(revText)

print reverse("Hello")

result

['o', 'l', 'l', 'e', 'H']
-1
source

Source: https://habr.com/ru/post/1681376/


All Articles