Adam Mitchell Adam Mitchell - 2 months ago 5
Python Question

Insert char from string into list in one line

I'm after a way to reduce the following code down to one line, I assume through list comprehension.

string = raw_input("String: ")
stringlist = []
for char in string:
stringlist.insert(0, char)

Answer

So, you basically want to reverse the string and create a list from its reversed version:

stringlist = list(reversed(raw_input("String: ")))

The following is even shorter, but probably a bit harder to read:

stringlist = list(raw_input("String: ")[::-1])

This code uses extended slices.