I’m trying to add whole words from one string to another if they contain a certain character:
mylist = ["hahah", "hen","cool", "breaker", "when"]
newlist = []
for word in mylist:
store = word #stores current string
if 'h' in word: #splits string into characters and searches for 'h'
newlist += store #adds whole string to list
print newlist
the result I expect is:
newlist = ["hahah","hen","when"]
but instead I’m getting:
newlist = ['h', 'a', 'h', 'a', 'h', 'h', 'e', 'n', 'w', 'h', 'e', 'n']
How do I get my expected result?
Use
append[docs]:Or shorter (using list comprehension [docs]):
Why does
newlist += storenot work?This is the same as
newlist = newlist + storeand is extending the existing list (on left side) by all the items in the sequence [docs] on the right side. If you follow the documentation, you will find this:In Python, not only lists are sequences, but strings are too (a sequence of characters). That means every item of the sequence (→ every character) is appended to the list.