10

Probably a simple question but I would like to parse the elements of one list individually to another. For example:

a=[5, 'str1'] 
b=[8, 'str2', a] 

Currently

b=[8, 'str2', [5, 'str1']] 

However I would like to be b=[8, 'str2', 5, 'str1']

and doing b=[8, 'str2', *a] doesn't work either.

bigboat
  • 249
  • 1
  • 4
  • 13

5 Answers5

28

Use extend()

b.extend(a)
[8, 'str2', 5, 'str1']
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
18

You could use addition:

>>> a=[5, 'str1']
>>> b=[8, 'str2'] + a
>>> b
[8, 'str2', 5, 'str1']
fredtantini
  • 15,966
  • 8
  • 49
  • 55
12

The efficient way to do this is with extend() method of list class. It takes an iteratable as an argument and appends its elements into the list.

b.extend(a)

Other approach which creates a new list in the memory is using + operator.

b = b + a
abhinav
  • 607
  • 6
  • 18
3
>>> a
[5, 'str1']
>>> b=[8, 'str2'] + a
>>> b
[8, 'str2', 5, 'str1']
>>> 

for extend() you need to define b and a individually...

then b.extend(a) will work

Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
0

You can use slicing to unpack a list inside another list at an arbitrary position:

>>> a=[5, 'str1'] 
>>> b=[8, 'str2'] 
>>> b[2:2] = a   # inserts and unpacks `a` at position 2 (the end of b)
>>> b
[8, 'str2', 5, 'str1']

Similarly you could also insert it at another position:

>>> a=[5, 'str1'] 
>>> b=[8, 'str2'] 
>>> b[1:1] = a
>>> b
[8, 5, 'str1', 'str2']
MSeifert
  • 145,886
  • 38
  • 333
  • 352