Skip to Content
Python 3 Object-Oriented Programming - Third Edition
book

Python 3 Object-Oriented Programming - Third Edition

by Dusty Phillips
October 2018
Beginner to intermediate
466 pages
12h 2m
English
Packt Publishing
Content preview from Python 3 Object-Oriented Programming - Third Edition

Unpacking arguments

There's one more nifty trick involving variable arguments and keyword arguments. We've used it in some of our previous examples, but it's never too late for an explanation. Given a list or dictionary of values, we can pass those values into a function as if they were normal positional or keyword arguments. Have a look at this code:

def show_args(arg1, arg2, arg3="THREE"): 
    print(arg1, arg2, arg3) 
 
some_args = range(3) 
more_args = { 
        "arg1": "ONE", 
        "arg2": "TWO"} 
 
print("Unpacking a sequence:", end=" ") 
 
show_args(*some_args) 
print("Unpacking a dict:", end=" ") 
 
show_args(**more_args) 

Here's what it looks like when we run it:

Unpacking a sequence: 0 1 2
Unpacking a dict: ONE TWO THREE  

The function accepts three arguments, one ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python 3 Object-Oriented Programming - Second Edition

Python 3 Object-Oriented Programming - Second Edition

Dusty Phillips

Publisher Resources

ISBN: 9781789615852Supplemental Content