Vinz243
Vinz243

Reputation: 9938

Python return several value to add in the middle of a list

Is it possible to make a function that returns several elements like this:

def foo():
  return 'b', 'c', 'd'

print ['a', foo(), 'e'] # ['a', 'b', 'c', 'd', 'e']

I tried this but it doesn't work

Upvotes: 2

Views: 82

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You can insert a sequence into a list with a slice assignment:

bar = ['a', 'e']
bar[1:1] = foo()
print bar

Note that the slice is essentially empty; bar[1:1] is an empty list between 'a' and 'e' here.

To do this on one line in Python 2 requires concatenation:

['a'] + list(foo()) + ['e']

If you were to upgrade to Python 3.5, you can use * unpacking instead:

print(['a', *foo(), 'e'])

See Additional Unpacking Generalisations in What's New in Python 3.5.

Demo (using Python 3):

>>> def foo():
...     return 'b', 'c', 'd'
...
>>> bar = ['a', 'e']
>>> bar[1:1] = foo()
>>> bar
['a', 'b', 'c', 'd', 'e']
>>> ['a'] + list(foo()) + ['e']
['a', 'b', 'c', 'd', 'e']
>>> ['a', *foo(), 'e']
['a', 'b', 'c', 'd', 'e']

Upvotes: 9

Gal Dreiman
Gal Dreiman

Reputation: 4009

You can also use this simple piece of code:

import itertools

def foo():
  return 'b', 'c', 'd'

l = ['a', foo(), 'e']
x=list(itertools.chain(*l))
print x 

Output: ['a', 'b', 'c', 'd', 'e']

Upvotes: -2

Related Questions