I have a 2d array in Python called "AllLines"
[['Suppliers', 'Spend', 'Test Field\n'],
['Dell Inc', '9000', '1\n'],
['Dell Computers', '9000', '2\n'],
['HBC Corp', '9000', '3\n'],
['HBC INC', '9000', '4']]
So, it is an array within an array. I need to append items to the inside array. To give me this:
[['NEW','Suppliers', 'Spend', 'Test Field\n'],
['N-E-W','Dell Inc', '9000', '1\n'],
['N-E-W---','Dell Computers', '9000', '2\n'],
['N-E---W','HBC Corp', '9000', '3\n'],
['N-W-W','HBC INC', '9000', '4']]
How do I achieve adding a new item to the inside arrays?
You can use a slice assignment:
>>> a = [['Suppliers', 'Spend', 'Test Field\n'], ['Dell Inc', '9000', '1\n']]
>>> a[0][0:0] = ["NEW"]
>>> a[1][0:0] = ["N-E-W"]
>>> a
[['NEW', 'Suppliers', 'Spend', 'Test Field\n'], ['N-E-W', 'Dell Inc', '9000', '1\n']]
Some timings:
>>> timeit.timeit(setup="a = [['Suppliers', 'Spend', 'Test Field'], ['Dell Inc', '9000', '1']]",
stmt="a[0][0:0] = ['NEW']", number=100000)
3.57850867468278
>>> timeit.timeit(setup="a = [['Suppliers', 'Spend', 'Test Field'], ['Dell Inc', '9000', '1']]",
stmt="a[0].insert(0, 'NEW')", number=100000)
4.941971139085055
>>> timeit.timeit(setup="a = [['Suppliers', 'Spend', 'Test Field'], ['Dell Inc', '9000', '1']]",
stmt="a[0] = ['NEW'] + a[0]", number=100000)
33.147023662906804
You can append or insert into them just as you would any other list e.g:
lst = list_of_lists[0]
lst.insert(0,'NEW')
Or, in one line:
list_of_lists[0].insert(0,'NEW')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With