Search code examples
pythonlistbroadcastmit-scratch

Python: List item is empty, code to detect if it is and then put in a place holder value?


Hey I'm writing a program that receives a broadcast from Scratch and then determines based on the broadcast, where to proceed. The code turns the broadcast(list item) into a string and then breaks that string into a list using .split(). The only problem is the broadcast may only be 1 word instead of 2. Is there a way to check if one of the list items from .split() is empty and then change it to a place holder value?

Where I am having trouble

scratchbroadcast =  str(msg[1])

    BroadcastList = scratchbroadcast.split()

    #starts the switch statement that interprets the message and proceeds
    #to the appropriate action
    v = BroadcastList[0]
    w = BroadcastList[1]
    if BroadcastList[1] == '':
        w = "na"

Solution

  • If BroadcastList contains only one word then BroadcastList will be a single-element list, e.g.

    >>> "foo".split()
    ['foo']
    

    Obviously we can't check whether the second item in the list is an empty string ''; there isn't a second element. Instead, check the length of the list:

    w = "na" if len(BroadcastList) == 1 else BroadcastList[1]
    

    Alternatively, use try to catch the IndexError (it's easier to ask for forgiveness than permission):

    try:
        w = BroadcastList[1]
    except IndexError:
        w = "na"