0

How would I create a list element from function call?

Not sure if this is possible, but I've tried to create a list element from a function when i create the list as i'm not sure of the elements up until runtime

So I have tried this:

>>>> def make_list_element():
        return 'd, e'

If i then try to create a list and call the function at the same time :

>>>> a = ['a', 'b', 'c', make_list_element().split(", ")]

And I get:

>>> a
>>> ['a', 'b', 'c', ['d', 'e']]

How could I achieve this:

>>> a
>>> ['a', 'b', 'c', 'd', 'e'] 

Preferably in the same statement as I create the list.

Many thanks

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Darth
  • 219
  • 2
  • 6
  • 18
  • 1
    Please always use the generic python tag, if your question is about a specific python version, then optionally include a version-specific tag – juanpa.arrivillaga Feb 08 '19 at 21:12
  • If you function returns a list, then you won't need the `split()` function just the asterisk – Joe Feb 08 '19 at 21:21

1 Answers1

2

In Python3, you can simply unpack the returned list like so:

a = ['a', 'b', 'c', *make_list_element().split(", ") ]

If you're on Python2, you will have to concatenate or extend the list:

a = ['a', 'b', 'c'] + make_list_element().split(", ")

or

a = ['a', 'b', 'c']
a.extend(make_list_element().split(", "))
emilyfy
  • 183
  • 1
  • 8
  • thanks for your answer but this errors with `>>> a = ['a', 'b', 'c', *make_list_element().split(", ")] File "", line 1 a = ['a', 'b', 'c', *make_list_element().split(", ")] ` – Darth Feb 08 '19 at 21:23
  • This seems to work though `a = ['a', 'b', 'c'] + make_list_element().split(", ")` Thanks – Darth Feb 08 '19 at 21:24