273

In a function that expects a list of items, how can I pass a Python list item without getting an error?

my_list = ['red', 'blue', 'orange']
function_that_needs_strings('red', 'blue', 'orange') # works!
function_that_needs_strings(my_list) # breaks!

Surely there must be a way to expand the list, and pass the function 'red','blue','orange' on the hoof? I think this is called 'unpacking'.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
AP257
  • 81,509
  • 84
  • 194
  • 260

3 Answers3

355
function_that_needs_strings(*my_list) # works!

You can read all about it here.

Flow
  • 22,860
  • 14
  • 95
  • 151
Jochen Ritzel
  • 99,912
  • 29
  • 194
  • 188
47

Yes, you can use the *args (splat) syntax:

function_that_needs_strings(*my_list)

where my_list can be any iterable; Python will loop over the given object and use each element as a separate argument to the function.

See the call expression documentation.

There is a keyword-parameter equivalent as well, using two stars:

kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)

and there is equivalent syntax for specifying catch-all arguments in a function signature:

def func(*args, **kw):
    # args now holds positional arguments, kw keyword arguments
Community
  • 1
  • 1
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
19

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)
vishes_shell
  • 20,161
  • 6
  • 65
  • 77