Adding to a Python list without making a list of lists
I start with an empty list and ask the user for a phrase. I want to add each character as one element of an array, but the way I do it is creating 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 I want:
['h', 'i', ' ', 'b' ... 'o', 'k', 'b', 'y', 'e']
+3
source to share
2 answers
The argument is .append()
not expanded, retrieved, or repeated. You should use .extend()
if you want all individual list items 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]
+9
source to share