ubuntu_noob
ubuntu_noob

Reputation: 2365

Append a space separated string to a list

I have a string and a list like this-

s = "ball apple snake car"
l = ['banana','toy']

Now I want to add it to an existing list so that the list looks like-

l = ['banana','toy','ball' ,'apple' ,'snake ','car']

Upvotes: 0

Views: 2664

Answers (3)

user3313834
user3313834

Reputation: 7837

>>> l += s.split()                                                                                                                             
>>> l                                                                                                                                          
['banana', 'toy', 'ball', 'apple', 'snake', 'car']
>>>

Upvotes: 0

alex_bits
alex_bits

Reputation: 752

Well it seems the simplest answer is to split the string by the spaces and append it to the list:

s="ball apple snake car"
l=['banana','toy']
s_list = s.split()
for item in s_list:
    l.append(item)

Upvotes: 0

Daniel Diekmeier
Daniel Diekmeier

Reputation: 3434

l = l + s.split(' ')
> ['banana', 'toy', 'ball', 'apple', 'snake', 'car']

With s.split(' '), you transform the string to a list of the words. With l +, you append that list to the end of the other list.

Upvotes: 2

Related Questions