In a list of multiword strings, extract second word

Question:

I have a list of strings. I would like to extract the second word in each string and save it to a new list. Some of the elements only have a single word.

l = ["OPTY PLN EXTRCT","MRKT COMMUNITY TABLE", "COMM", "EXT OPTY EMP"] 

Desired Output:

output = ['PLN', 'COMMUNITY', 'OPTY']

A List Comprehension works to extract the first word.

[i.split()[0] for i in l] 

The code below throws an index error because there are elements in the list with only one word.

[i.split()[1] for i in l]

If the element only has a single word, I would like the iteration to skip over it and continue on.
I am playing with a Try and except but have not successfully gotten it to work.

Asked By: Ryan Conway

||

Answers:

You could just add if condition to your comprehension like ... if len(i.split()) > 1] however that would require you to split your words twice, here we’re doing it once for every element of l by using map().

l = ["OPTY PLN EXTRCT","MRKT COMMUNITY TABLE", "COMM", "EXT OPTY EMP"]

output = [words[1] for words in map(str.split, l) if len(words) > 1]

Outputs:

['PLN', 'COMMUNITY', 'OPTY']

Alternatively if you’re using python3.8 we could use new := notation.

output = [words[1] for i in l if len(words := i.split()) > 1]
Answered By: Filip MÅ‚ynarski
words = [w.split(None, 3)[1] for w in l if any(x.isspace() for x in w.strip())]

This will exclude a word from the list if it is an empty string, consists only of whitespaces and if it does contain characters but has no whitespaces in between. Therefore you should have at least two words for it to split and extract. Note that my splitting solution stops the splitting after the second word, so you may have a lot of them in the string, but split() will not lose time by processing them all.

Answered By: Dalen
output = []
for word in l:
    second = word.split()
    if len(second) > 1:
        output = output + [second[1]]

print(output)

Answered By: Hemanth Kumar