I start out with an empty list and prompt the user for a phrase. I want to add each character as a single element of the array, but the way I'm doing this creates a list of lists.
myList = []
for i in range(3):
myPhrase = input("Enter some words: ")
myList.append(list(myPhrase))
print(myList)
I get:
Enter some words: hi bob
[['h', 'i', ' ', 'b', 'o', 'b']]
Enter some words: ok
[['h', 'i', ' ', 'b', 'o', 'b'], ['o', 'k']]
Enter some words: bye
[['h', 'i', ' ', 'b', 'o', 'b'], ['o', 'k'], ['b', 'y', 'e']]
but the result I want is:
['h', 'i', ' ', 'b' ... 'o', 'k', 'b', 'y', 'e']
The argument to .append()
is not expanded, extracted, or iterated over in any way. You should use .extend()
if you want all the individual elements of a list to be added to another list.
>>> L = [1, 2, 3, 4]
>>> M = [5, 6, 7, 8, 9]
>>> L.append(M) # Takes the list M as a whole object
>>> # and puts it at the end of L
>>> L
[0, 1, 2, 3, [5, 6, 7, 8, 9]]
>>> L = [1, 2, 3, 4]
>>> L.extend(M) # Takes each element of M and adds
>>> # them one by one to the end of L
>>> L
[0, 1, 2, 3, 5, 6, 7, 8, 9]
I think you're going about the problem the wrong way. You can store your strings as strings then iterate over them later a character time as necessary:
foo = 'abc'
for ch in foo:
print ch
Outputs:
a
b
c
Storing them as a list of characters seems unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With