Creating list from a String and display the elements in reverse order

In this program, we will ask the user to enter any string. Storing the input string in the variable and adding each string character to a list.

The first step is to ask the user to input the string, and for that, we will be using the input() function.

str  = input('Enter a string: ')

Create an empty list. 

strlist= []

We can use the len() function to find the number of characters in a string. This is optional.

print('Length of a string: ',len(str))

A for loop can now be used to access every character in a string and append it to a list.

for s in str:
    strlist.append(s)

Print elements from a list.

print(strlist)

Calculate the length of the string and assign it to a variable. 

l = len(strlist)

Make a variable that has the value -1.

i = -1

Now, create a second empty list where we are going to arrange elements in reverse order.

revlist =[]

Use a while loop to access each item from the first list, starting with the last element and making it the first element of the second list. The value -1 denotes the list’s final element. 

while i >= -l:
    revlist.append(strlist[i])
    i-=1

Finally, print elements from the second list in reverse order.

print(revlist)

Output

Enter a string: London
Length of a string:  6
['L', 'o', 'n', 'd', 'o', 'n']
['n', 'o', 'd', 'n', 'o', 'L']

Process finished with exit code 0

Complete Code

str  = input('Enter a string: ')
strlist= []
print('Length of a string: ',len(str))
for s in str:
    strlist.append(s)

print(strlist)
l = len(strlist)
i = -1
revlist =[]
while i >= -l:
    revlist.append(strlist[i])
    i-=1
print(revlist)
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s