0

When declaring a list literal in Python, is it possible to merge an existing list into the declaration? For example:

l = [1, 2, 3]
n = [10, 20, 30, l, 50, 60, 70]

This results in the following:

[10, 20, 30, [1, 2, 3], 50, 60, 70]

Note that the list l itself has been added as a single element, but what I really want is for l's elements to be added individually to the target list, like this:

[10, 20, 30, 1, 2, 3, 50, 60, 70]
Amr Bekhit
  • 4,613
  • 8
  • 34
  • 56

2 Answers2

1

As of Python 3.5 (See https://www.python.org/downloads/release/python-350/, PEP448), This can be done using Python's unpack operator, which is an asterisk before the list:

l = [1, 2, 3]
n = [10, 20, 30, *l, 50, 60, 70]

The result is:

[10, 20, 30, 1, 2, 3, 50, 60, 70]
Amr Bekhit
  • 4,613
  • 8
  • 34
  • 56
0

This will works with l on any place

from itertools import chain   
for i in n:
   if isinstance(i, list):
      b+=list(chain(i))
   else:
      b+=[i]
nick_gabpe
  • 5,113
  • 5
  • 29
  • 38