By AP257

2010-08-13 19:40:06 8 Comments

I think 'unpack' might be the wrong vocabulary here - apologies because I'm sure this is a duplicate question.

My question is pretty simple: 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?


@Jochen Ritzel 2010-08-13 19:40:59

function_that_needs_strings(*my_list) # works!

You can read all about it here.

@vishes_shell 2016-09-04 19:11:35

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)

@answerSeeker 2017-10-05 02:12:36

how can I do the same with python 2.7 or 3.4?

@azalea 2019-01-02 18:48:17

@answerSeeker not efficient, but function_that_needs_strings(*(a+b))

@Martijn Pieters 2013-12-17 19:37:36

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


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'}

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

Related Questions

Sponsored Content

21 Answered Questions

[SOLVED] What are metaclasses in Python?

21 Answered Questions

28 Answered Questions

[SOLVED] How do I concatenate two lists in Python?

30 Answered Questions

[SOLVED] Finding the index of an item in a list

  • 2008-10-07 01:39:38
  • Eugene M
  • 3949173 View
  • 3236 Score
  • 30 Answer
  • Tags:   python list indexing

40 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

27 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray
  • 2931425 View
  • 3234 Score
  • 27 Answer
  • Tags:   python list

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

20 Answered Questions

62 Answered Questions

[SOLVED] Calling an external command from Python

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 4453951 View
  • 3472 Score
  • 21 Answer
  • Tags:   python directory

Sponsored Content