15

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.

0

5 Answers 5

41

Use extend()

b.extend(a) [8, 'str2', 5, 'str1'] 
Sign up to request clarification or add additional context in comments.

Comments

24

You could use addition:

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

1 Comment

This is definitely the nicest option. Thanks
18

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 

1 Comment

This is definitely the better solution.
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

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.