Michael
Michael

Reputation: 16122

How to add a string to list inside other list on python 2.7

I want to add 'new_str' to my list inside another list. Here is my code:

>>>l = ['some_str', ['some_new_str']]
>>>print l
['some_str', ['some_new_str']]
>>>l1 = l[1].append('new_str')
>>>print l1
None

l[1].append('new_str') instead of add a new string into my list inside other list, it has printout 'None'.

So how can I add a string to list inside other list on python 2.7?

Note: the output should look like this: ['some_str', ['some_new_str', 'new_str']]

Thanks.

Upvotes: 2

Views: 267

Answers (1)

TerryA
TerryA

Reputation: 59974

list.append() does not return anything. It appends the item in place, without actually returning the new list.

Because it does not return anything, Python defaults this to None (that is why None is printed)

You can simply do:

>>> l[1].append('new_str')

Upvotes: 6

Related Questions