Home > Net >  Iterating over a list of strings that may be of length 1
Iterating over a list of strings that may be of length 1

Time:01-11

Let's say I generate a list of strings:

def printList(list)
    for i in list:
        print(i)

string = 'hello,world,!'
strings = string.split(',')
printList(strings)

This works fine. However, if the string is only one element long, or I want to call printList with a type that is not iterable, then this falls apart. Consider the following (more relevant) example:

my_list=[]
def add_items_filtered(items)
    for item in items:
        if item > 5: #arbitrary filter
            my_list.append(item)

add_items_filtered([4,5,6,7]) #this works fine
add_items_filtered(6) #this fails

The issue here is that the item I sent is not "iterable". I can work around this with:

if not isinstance(items, list):
    items=[items]

But this seems like a hack. Is the only real way to do this by forcing the caller of this function to send me in a list? It seems counterintuitive to be roadblocked by such a simple issue.

CodePudding user response:

If you want a workaround, use

def add_items_filtered(*items):

Then you can pass arguments like

add_items_filtered(4,5,6,7)
add_items_filtered(6)

Otherwise, you'll have to check types, and there is nothing wrong with looping over a list of one element.

CodePudding user response:

You cannot iterate through an integer since it is a non iterative datatype. An alternative way of writing the add_items_filtered function would be using the is instance to check if items is an iterative datatype or not.

def add_items_filtered(items):
    if isinstance(items, int):
        if items > 5:
            my_list.append(items)
    elif isinstance(items, (set, list)):
        for item in items:
            if item > 5: #arbitrary filter
                my_list.append(item)
    else:
        return
  •  Tags:  
  • Related