-5

If I have a string:

a = 'hello'

How do I convert it into a list?

a = ['h', 'e', 'l', 'l', 'o']
V.ictor
  • 13
  • 1

2 Answers2

4

A string is an iterable, and a list can be constructed from an iterable. So all you need is

a = list(a)
print(a)

Output:

['h', 'e', 'l', 'l', 'o']

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Ow oke that works, Thanks! – V.ictor Oct 12 '15 at 13:43
  • Note: a list comprehension `[c for c in a]` should be [faster](http://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops) – Pynchia Oct 12 '15 at 14:14
  • @Pynchia I have heard the opposite. If you have any evidence to back up that claim it would be good to see it! (I can't find it in the link you posted.) – juanchopanza Oct 12 '15 at 16:03
  • @juanchopanza I just timed it and it's kind of difficult to tell. `python3 -mtimeit -s'l=list(range(1000000))'` and `python3 -mtimeit -s'l=[el for el in range(1000000)]'`. Sometimes one or the other is faster. I must have misunderstood a discussion carried out here a few days ago [here](http://stackoverflow.com/questions/33001611/join-one-word-lines-in-a-file) – Pynchia Oct 12 '15 at 21:36
  • @Pynchia Same here, I never managed to spot a significant difference between the two (in python 2, haven't tried python 3.) – juanchopanza Oct 12 '15 at 21:37
  • @juanchopanza alright. Thank you for making me check. Good night – Pynchia Oct 12 '15 at 21:46
0

Tried to do it differently

Code:

map(None,"sart")#for python 2.x
#list(map(None,"sart")) for python 3.x

Output:

['s', 'a', 'r', 't']
The6thSense
  • 8,103
  • 8
  • 31
  • 65