Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a column to a 2 dimensional array

Tags:

python

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?

like image 758
fredy kruger Avatar asked May 18 '26 20:05

fredy kruger


2 Answers

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
like image 150
Tim Pietzcker Avatar answered May 26 '26 04:05

Tim Pietzcker


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')
like image 35
mgilson Avatar answered May 26 '26 03:05

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!