Adam Mitchell Adam Mitchell - 1 year ago 125
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download