Python – List Comprehension using .split()

List comprehension allows you to create a new modified list from an old list. My example is a tad tricky to someone new, the .split() makes it all happen and I added some other things inside the list comprehension too.

So blah is set to a string, then a temp list (bleh) is made so we can check each index using .split() which defaults to a space separator so we can filter by words. Without the .split() the for loop would check each character and not words. Output is a modified bleh list with all remaining words in capitols and we replace the ? with a !.

blah = 'I want to go to hell or Alaska?' # print(blah) to see why .split() is used
bleh = [c.upper().replace('?', '!') for c in blah.split() if c != 'hell' and c != 'or']

# ['I', 'WANT', 'TO', 'GO', 'TO', 'ALASKA!']

# To print like a new string, notice we have a space ' '.join() joining each list item from example above together with a space in between each word.
print(' '.join(bleh))


I love list comprehension.

Leave a Comment