Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over *args?

I have a script I'm working on where I need to accept multiple arguments and then iterate over them to perform actions. I started down the path of defining a function and using *args. So far I have something like below:

def userInput(ItemA, ItemB, *args):
    THIS = ItemA
    THAT = ItemB
    MORE = *args

What I'm trying to do is get the arguments from *args into a list that I can iterate over. I've looked at other questions on StackOverflow as well as on Google but I can't seem to find an answer to what I want to do. Thanks in advance for the help.

like image 753
Paul Avatar asked Mar 05 '12 15:03

Paul


1 Answers

To get your precise syntax:

def userInput(ItemA, ItemB, *args):
    THIS = ItemA
    THAT = ItemB
    MORE = args
    
    print THIS,THAT,MORE
    
    
userInput('this','that','more1','more2','more3')

You remove the * in front of args in the assignment to MORE. Then MORE becomes a tuple with the variable length contents of args in the signature of userInput

Output:

this that ('more1', 'more2', 'more3')

As others have stated, it is more usual to treat args as an iterable:

def userInput(ItemA, ItemB, *args):    
    lst=[]
    lst.append(ItemA)
    lst.append(ItemB)
    for arg in args:
        lst.append(arg)

    print ' '.join(lst)
    
userInput('this','that','more1','more2','more3') 

Output:

this that more1 more2 more3
like image 119
the wolf Avatar answered Sep 21 '22 13:09

the wolf