0

I have tried as below , it can be done using list comprehension [also without using in-build functions and techniques like [::-1] ], but want to do it using nested for loops as below ?

l=['temp','test']
l1=[]
for t in l:
  for i in t:
      l1.append(str(i[::-1]))
print(l1)

input: ['test','temp']
required output : ['pmet','tset']

6 Answers 6

3

In order to reverse the order of the elements in the list, you can use reverse:

for i in reversed(array):
     print(i)

Or, you can use array.reverse().

in order to reverse each string, you can use [::-1], for example:

txt = "Hello World"[::-1]
print(txt)

output:

dlroW olleH

Looking at the code you added, you can do something like this:

l=['temp','test']
reverse_l=[]
reverse_l = [item[::-1] for item in l] # This is list comprehensions, you can read about it in the link at the end of the answer
reverse_l.reverse()
print(l)
print(reverse_l)

output:

['temp', 'test']
['tset', 'pmet']

A solution without list comprehension:

l=['temp','test']
reverse_l=[]
for item in l:
    item = item[::-1]
    reverse_l.append(item)
reverse_l.reverse()
print(l)
print(reverse_l)

You can find information about list Comprehensions in python here.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks Eyal , actually i was looking for an answer without using list comprehension . what will be the approach ? i understand outer for loop is for each element in the list and the inner for loop will be for traversing the each list element .
@SameerKumar I added a solution without using list comprehension. In the future, please don't change the question's requirements after people answered.
1

Using nested loops:

l=['temp','test']
print([''.join([w[i] for i in range(len(w)-1, -1, -1)]) for w in reversed(l)])

Output:

['pmet', 'tset']

2 Comments

Your input is not the same as the OP.
Thanks Joan , can help me by simplifying the list comprehensions "[''.join([w[i] for i in range(len(w)-1, -1, -1)]" , i mean can you please simplify it without using list comprehension .
0

try this

l=['temp','test']
l1=[]
for t in l:
  l1.append(t[::-1])
print(l1)

Comments

0

You don't need a nested loop:

l = ['temp', 'test']
l1 = [
    word[::-1]
    for word in l
]
print(l1)

output:

['pmet', 'tset']

Comments

0

You can try the following :

input_list = ['test', 'temp']
input_list.reverse()
print(list(map(lambda x: x[::-1], input_list)))

Comments

0
for i in range(len(l)):
    l[i] = l[i][::-1]
l = l[::-1]

you don't need nested loops for desired output you have given.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.