0

I am trying to reverse a list of strings. For instance

one two three

will be output as

three two one

I have tried this

[x for x in range(input()) [" ".join(((raw_input().split())[::-1]))]]

but I am getting an error:

 TypeError: list indices must be integers, not str
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
saleem
  • 121
  • 4
  • Possible duplicate of [How can I reverse a list in python?](http://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python) – rfj001 Dec 24 '15 at 18:17
  • do you want the result in a string or a list – NendoTaka Dec 24 '15 at 18:17
  • I need to achieve this in single line and need the output as a string. I know to reverse a string. The issue is when I try to create a single line code. – saleem Dec 24 '15 at 18:21

4 Answers4

2
>>> ' '.join("one two three".split()[::-1])
'three two one'

you can use like this,

>>> ' '.join(raw_input().split()[::-1])
one two three
'three two one'
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
2
>>> t="one two three"
>>> " ".join( reversed(t.split()) )
'three two one'
Copperfield
  • 8,131
  • 3
  • 23
  • 29
1

If you want to use raw_input() try this:

>>> " ".join((raw_input().split())[::-1])
one two three
'three two one'
Delimitry
  • 2,987
  • 4
  • 30
  • 39
0

To actually address your code and why it fails with an error, you are trying to index the range list with a str i.e " ".join((raw_input().split()[::-1])):

range(input())[" ".join((raw_input().split()[::-1]))]

You would need to loop over the inner list for your code to run without error:

 [s for x in range(input()) for s in [" ".join((raw_input().split()[::-1]))]]

Which would output something like:

2
foo bar
foob barb
['bar foo', 'barb foob']

And can simplify to:

[" ".join((raw_input().split()[::-1])) for _ in range(input())]

If you want a single string just call join on the outer list, I would also recommend using int(raw_input(... generally but I know you are code golfing.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321