-4

This is my code I have come up with trying to reverse these strings

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)

As of now, it only prints the list backwards like this:

John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington 

I need it to output the list like:

notgnihsaW egroeG
smadA nhoJ

and so on

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Dan Shay
  • 11
  • 3

4 Answers4

0

Try this:

>>> reversedPresidents = [p[::-1] for p in presidents]
>>> print(reversedPresidents)
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
>>> 
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

Beauty of Recursion :

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

def reverse_list(list_1):
    for item in list_1:
        def reverse(word):
            if len(word)==0:
                return word
            else:
                return reverse(word[1:]) + word[0]
        print(reverse(item))
print(reverse_list(presidents))

output:

 notgnihsaW egroeG
 smadA nhoJ 
 nosreffeJ samohT 
 nosidaM semaJ 
 eornoM semaJ 
 smadA ycniuQ nhoJ 
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
0

You can try this also:

>>> presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

>>>> print(["".join(reversed(x)) for x in presidents])
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

Try this:

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , 
" James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=[]
for ch in presidents: 
     reversedPresidents.append(ch[::-1])

print(reversedPresidents)

 [' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM 
  semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
Mike
  • 185
  • 1
  • 9