7

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']
Heitor Chang
  • 6,038
  • 2
  • 45
  • 65

2 Answers2

20

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]
jscs
  • 63,694
  • 13
  • 151
  • 195
3

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.

spencercw
  • 3,320
  • 15
  • 20
  • You're right. I can just concatenate them, a + b, then treat the new string as an array. In the bigger application, I am holding objects in an array that need to match each character of this big string, so I was thinking I needed each character as a separate thing in an array. – Heitor Chang Apr 03 '12 at 18:21