1

Python dont return a new list when you work on methods of class list, so is there a way to do one-liners in python without the use of list comprehension or lambda function?

For exemple, I cant do:

def foo():
    return "Euston saw I was not Sue".split().reverse()

Because reverse dont return a new list, I need to assign "Euston saw I was not Sue".split() to a variable and then apply reverse to this variable and then return a, like this:

def foo():
    r = "Euston saw I was not Sue".split()
    r.reverse()
    return r

Is there a solution to do something like the first code?

Thanks.

vildric
  • 910
  • 1
  • 8
  • 22
  • `.split()[::-1]`, but the `.reverse` is nice and explicit... – Jon Clements Mar 15 '15 at 17:04
  • You can also use `list(reversed(some_string.split()))`. – ely Mar 15 '15 at 17:08
  • Hum ok... Dunno why every other language (ruby,haskell etc) allow ` "Euston saw I was not Sue".split().reverse()`, Im like disapointed by python lol, but thanks for your answer. – vildric Mar 15 '15 at 17:14
  • 1
    @vildric Python *does* provide the same thing. The name of it in Python is `.split()[::-1]`. Other languages call it "reverse" while Python calls in `[::-1]` and uses the word `reverse` to mean something different. You could equally as well fault the other languages for not choosing to express reverse intrinsically through list slicing syntax. Also, I don't know about Ruby, but with Haskell at least the `List` data type (e.g. `[]`) is a lazy linked list, with `head` and `tail` amenable to tail-call optimized recursive reversal, which is not appropriate for Python's `list` which is an `array`. – ely Mar 15 '15 at 17:28
  • Right for `[::-1]`, but I find it kind of a hack more than anything else. For example, what do you do if you have a `a` an unsorted list and you want to sort this list and put it in the b variable without modify the original list? Again in ruby (who is a language that I dont really like) you just do `a = [2,3,1,5,4]; b = a.sort()` and its finish. In Python, you'll need to use the builtin function sorted like `b=sorted(a)`. Why the hell its like that? – vildric Mar 15 '15 at 21:43

0 Answers0