Search code examples
pythonlistisinstance

Python isinstance not working with if statement.


I have a list of addresses. Some address have the street, city, state, zip and others just have city, state, and zip. I made a for loop to put each element into a separate variable. The problem is I am not getting the right output so I put an if statement with isinstance(address[3], int], I did this to check if the 4th element is there then execute the code but it's just not working. I'll post below to show what I am doing and let me know where I messed up. The first address has a street and the second doesn't, so I want to substitute the address for "-".

address = [['123 street name, New Orleans, LA, 12345'],['New Orleans, LA, 12345']]
if isinstance(address[3], int):
    street = address[0]
    city = address[1]
    city = city.lstrip()
    state = address[2]
    state = state.lstrip()
    zip_code = address[3]
else:
    street = "-"
    city = address[0]
    city = city.lstrip()
    state = address[1]
    state = state.lstrip()
    zip_code = address[2]

Solution

  • There are multiple issues with your code.. first of all address is a list of lists length one. Second, if you'd like to check if the address contains a zip code, both of your examples do, but you can't access them separately from the other data since it is stored as a String right now. Try separating the elements and actually storing them as either Strings or ints. The next issue is that you can't check an element which does not exist. If you know the other data must be present, you can check the length of the list. In summary, use these changes:

    addresses = [['123 street name', 'New Orleans', 'LA', 12345],['New Orleans', 'LA', 12345]]
    
    for address in addresses:
        if len(address) > 3:
            street = address[0]
            city = address[1]
            city = city.lstrip()
            state = address[2]
            state = state.lstrip()
            zip_code = address[3]
        else:
            street = "-"
            city = address[0]
            city = city.lstrip()
            state = address[1]
            state = state.lstrip()
            zip_code = address[2]