On May 20, 12:55 am, Laurent Luce <laurentluc...@yahoo.com> wrote:
> I had a simple loop stripping each string but I was looking for
> something concise and efficient. I like the following answer:
> x = [s.rstrip('\n') for s in x]

Your initial requirement stated that you needed this to happen in-
place. What you're doing here is creating a completely new list and
then assigning it to x. While this is most likely what you want, note
that this will not update any other reference to that list:

>>> x = ['test\n', 'test2\n', 'test3\n']
>>> y = x
>>> x = [s.rstrip() for s in x]
>>> x
['test', 'test2', 'test3']
>>> y
['test\n', 'test2\n', 'test3\n']

To perform the same operation in-place, you can use the slice operator
to assign to the list object rather than to the label:

>>> x = ['test\n', 'test2\n', 'test3\n']
>>> y = x
>>> x[:] = [s.rstrip() for s in x] # note the slice operator
>>> x
['test', 'test2', 'test3']
>>> y
['test', 'test2', 'test3']

The latter example is especially important if you have more than one
reference to the list you're modifying and wish them all to have the
updated value.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to