Search code examples
pythonstringlistsplitlist-comprehension

In a list of multiword strings, extract second word


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.


Solution

  • 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]