Best way to inplace alter a list going into postgres

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue May 31 01:58:25 EDT 2016


On Tuesday 31 May 2016 14:27, Sayth Renshaw wrote:

> 
> Hi
> 
> What is the best way to inplace alter a list going into a postgres database

Is it relevant where it is going?

What you do with the list after you alter it is irrelevant -- perhaps you will 
insert it into an Oracle database, or a place it in a dict, or print it. The 
only reason it might be relevant is if Postgres can do the work for you, so you 
don't need to split it in Python. And that's probably a question for a Postgres 
group, not a Python group.


> using split but being sure that the order of items remains correct.

To modify a list *in place* is tricky. You can use slicing, which is easy, but 
because the size of the list changes you need to work backwards from the end.

I will use 'x' for fields that don't change, and suppose you wish to split 
fields 9, 10, 11 and 12. (Remember that Python counts starting from 0, not 1.)

L = ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 
     '11-3-1-4 $72390.00',
     '2-0-0-2 $8970.00', 
     '3-2-0-0 $30085.00', 
     '3-1-0-0 $15450.00',
     'x', 'x', 'x'
     ]
for index in (12, 11, 10, 9):  # must process them in *reverse* order
    item = L[index]
    values = item.replace('-', ' ').split()
    L[index:index+1] = values  # slice assignment


Perhaps a better way is to build a new list:

L = ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', '11-3-1-4 $72390.00',
     '2-0-0-2 $8970.00', '3-2-0-0 $30085.00', '3-1-0-0 $15450.00',
     'x', 'x', 'x']
new = []
for i, item in enumerate(L):
    if i in (9, 10, 11, 12):
        values = item.replace('-', ' ').split()
        new.extend(values)
    else:
        new.append(values)



You can then replace L with new *in-place* with a slice:

L[:] = new

or just use new instead.



-- 
Steve




More information about the Python-list mailing list