v0idation
v0idation

Reputation: 45

Make string in python behave like a list of one item

I have a validate function which checks the members of a list returned from another function against a control list of permitted values. This works fine except in the case where the returned list contains a single string. Python then interprets that string as a list of characters. Can I make it process it as though it were a list with only one item? Here is the function:

def validate(returned_list, control_list):
    for y in range(len(returned_list)):
       tf = False
       for x in range(len(control_list)):
           if returned_list[y] == control_list[x]:
               tf = True
               break
       if tf == False:
           return returned_list[y]
    return "OK"

Upvotes: 0

Views: 308

Answers (3)

v0idation
v0idation

Reputation: 45

Based on all the comments, here is the revised function:

def validate(returned_list, control_list):
    if isinstance(returned_list, basestring):
        returned_list = [returned_list]
    for x in returned_list:
        for y in control_list:
            if x == y:
                break:
        else:
            return x
    return None

Upvotes: 0

itzMEonTV
itzMEonTV

Reputation: 20359

Can you try this:

def validate(returned_list, control_list):
    returned_list = returned_list if isinstance(returned_list, list) else [returned_list]
    for y in range(len(returned_list)):
       tf = False
       for x in range(len(control_list)):
           if returned_list[y] == control_list[x]:
               tf = True
               break
       if tf == False:
           return returned_list[y]
    return "OK"

Upvotes: 1

deets
deets

Reputation: 6395

You need to check for the type here. Like this:

 def polymorphic(arg):
     if isinstance(arg, basestring):
         arg = [arg]
     for item in arg:
         print item

This is IMHO one of the few instances where you should perform a check like this. Normally, this is discouraged for good reasons, as you'd end up strong-arming Python into something it isn't - a statically typed language. However, the iteration-behaviour of strings makes it necessary every now and then.

Upvotes: 1

Related Questions