Understanding the Code for Reverse String Listing

Asked 2 years ago, Updated 2 years ago, 17 views

list1=[ ]
list2 = [ ]
for c in "iterable":
    list1.append(c)
whilelen(list1)>0:
    j=-1# This and
    d = list1.pop(j)
    j+=1#I don't need this.
    list2.append(d)
print(list2)

The string was reversed by the code.
①Can you write a little shorter?

Actually, I wanted to do the same thing using only the for loop instead of using the while loop, but
I didn't know how to put the index character of the variable c in the append.
②Is it possible to write a code for inserting a string from the end using the append method with only for loop?
(add to question *2)
In this question, I asked if I could rewrite the opening code with three elements: for, append, and how to specify the index (if required separately).
Therefore, as you mentioned in the comment, if you can specify the index by using the len function, it doesn't matter whether the len function is included or not.

These are the two questions.

python

2022-09-30 19:00

3 Answers

If you simply want to lick a character after a string, you can do the following:Like OOper's answer, we index and fill the last character of the string in order.

s="string"
l = [ ]
for i in range (len(s):
  l.append(s[len(s)-i-1])

Also, I'm not sure if it fits this requirement, but if you can use slice to partially retrieve the list, and if you can specify the starting point, ending point, step number, and negative values for slice, you can write as follows:

s=list("string")
l=s[::-1]


2022-09-30 19:00

"Regarding ""Can't you write a little shorter"" in の, let me pass, and just だけ, but how about this?"

 str = "string"
list = [ ]
for i in range (len(str)-1, -1, -1):
    list.append(str[i])

"There was an addition saying ""How to specify an index"", so I interpreted it as acceptable to specify the index of the string and extract the characters."


2022-09-30 19:00

How about this one?
You can reduce the number of lines and it's easy to understand.

l=list("Hello")
l. reverse()

print(l)


2022-09-30 19:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.