Sameer Kumar
Sameer Kumar

Reputation: 3

how can i reverse a list as well as its string elements using python using nested for loops?

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

Upvotes: 0

Views: 91

Answers (6)

user3980558
user3980558

Reputation:

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.

Upvotes: 3

Joan Lara
Joan Lara

Reputation: 1396

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

Upvotes: 1

AKSHAY PANDYA
AKSHAY PANDYA

Reputation: 91

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.

Upvotes: 0

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

You can try the following :

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

Upvotes: 0

Boseong Choi
Boseong Choi

Reputation: 2596

You don't need a nested loop:

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

output:

['pmet', 'tset']

Upvotes: 0

Manali Kagathara
Manali Kagathara

Reputation: 761

try this

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

Upvotes: 0

Related Questions