0

I'm using PyCharm on Windows (and very new to Python)

I'm a 'what happens when I try this?' person and so I tried:

alist = []
alist += 'wowser'

which returns ['w', 'o', 'w', 's', 'e', 'r']

Is there any reason not to convert a string to a list of individual characters like this? I know I could use For loop method OR I could .append or +concatenate (both seem to be too tedious!!), but I can't find anything that mentions using += to do this. So, since I'm new, I figure I should ask why not to do it this way before I develop a bad habit that will get me into trouble in the future.

Thanks for your help!

GBouffard
  • 1,125
  • 4
  • 11
  • 24
Bethany
  • 21
  • 1
  • 4
    `list('wowser')` would do just that... (and actually a python string is already a [immutable] sequence of individual characters). – hiro protagonist Oct 06 '19 at 20:13
  • 2
    *"Is there any reason not to convert a string to a list of individual characters like this?"* -- Yes, if you feel awkward enough about it to ask here, imagine a co-worker or your future self staring down that snippet wondering whether `+=` corresponds to `extend` or `append` (and why you are torturing them like that) when @hiroprotagonist 's `list('wowser')` or the equally more readable comprehension was available. – user2390182 Oct 06 '19 at 20:18

2 Answers2

0

I think this would help: Why does += behave unexpectedly on lists?

About the question "Is there any reason not to convert a string to a list of individual characters like this". I think it depends on your purpose. It will be quite convenient if you need to split the letters. If you don't want to split the letters, just don't use it.

Thuat Nguyen
  • 272
  • 3
  • 15
0

String is a type of array so it behaves like an array as lists do.

>>> # This way you would do it with a list:
>>> list('wowser')
['w', 'o', 'w', 's', 'e', 'r']
>>> lst=list('wowser')
>>> a='w'
>>> a is lst[0]
True

>>> # The String Version:
>>> strng = 'wowser'
>>> a is strng[0]
True

>>> # Iterate over the string like doing it with lists:
>>> [print(char) for char in 'wowser']
w
o
w
s
e
r
>>> [print(char) for char in ['w', 'o', 'w', 's', 'e', 'r']]
w
o
w
s
e
r

w3schools.com docs.python.org

Frank
  • 1,959
  • 12
  • 27