Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to a Python list without making list of lists

Tags:

python

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']
like image 982
Heitor Chang Avatar asked Apr 03 '12 18:04

Heitor Chang


2 Answers

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]
like image 58
jscs Avatar answered Oct 04 '22 15:10

jscs


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.

like image 38
spencercw Avatar answered Oct 04 '22 16:10

spencercw