How To Add A Item In A List Of List Using Python
Is there any way to add a item to a list of list using python. As an example there is a list as below: test_list = [['abc','2'],['cds','333'],['efg']] I want to add a item '444'
Solution 1:
Yes that is definitely something you can do.
You simply access the list object that you want to add another item to by its index, and then call .append()
on that list object with the new value.
test_list = [['abc','2'], ['cds','333'], ['efg']]
test_list[2].append('444')
# test_list is now: [['abc','2'], ['cds','333'], ['efg', '444']]
Solution 2:
test_list = [['abc','2'],['cds','333'],['efg']]
test_list[2].insert(1,"444")
print(test_list)
Solution 3:
Try using append
, append
does your job:
>>> test_list = [['abc','2'],['cds','333'],['efg']]
>>> test_list[2].append('444')
>>> test_list
[['abc', '2'], ['cds', '333'], ['efg', '444']]
>>>
Or use +=
, that adds stuff together, but two lists, so do:
>>> test_list = [['abc','2'],['cds','333'],['efg']]
>>> test_list[2] += ['444']
>>> test_list
[['abc', '2'], ['cds', '333'], ['efg', '444']]
>>>
append
is a builtin python list method, here is the documentation for it, and for +=
, that is a builtin addition operator, see the documentation for it.
Solution 4:
Above Three are absolutely correct. But I want to add One thing If you want to add an element in a list of list and you don't know the ending index you can do something like,
>>> test_list = [['abc','2'],['cds','333'],['efg']]
>>> test_list[-1].append('444')
>>> test_list
[['abc', '2'], ['cds', '333'], ['efg', '444']]
Post a Comment for "How To Add A Item In A List Of List Using Python"