Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating list in-place

I have a list of strings, some of them ends with new line symbol. I want to modify this list by removing \n from strings which ends with it. For this purpose I use the following code:

aList = ['qwerttyy\n', '123454\n', 'zxcv']

for s in aList:
    if s.endswith('\n'):
    s = s[: -1]
        print(s)

The output is the following:

    qwerttyy
    123454
    >>> aList
    ['qwerttyy\n', '123454\n', 'zxcv']

So the original list wasn't changed though list is mutable object. What is the reason of such behavior?

like image 277
Aleks Lee Avatar asked Jan 23 '26 14:01

Aleks Lee


2 Answers

You can use slice assignment and a list comprehension:

>>> foo = aList = ['qwerttyy\n', '123454\n', 'zxcv']
>>> aList[:] = [s[:-1] if s.endswith('\n') else s for s in aList]
>>> foo                         #All references are affected.
['qwerttyy', '123454', 'zxcv']
>>> aList
['qwerttyy', '123454', 'zxcv']

Your code didn't work because it is equivalent to:

s = aList[0]
if s.endswith('\n'):
    s = s[: -1]
s = aList[1]
if s.endswith('\n'):
    s = s[: -1]
...

i.e You're updating the variable s, not the actual list item

like image 164
Ashwini Chaudhary Avatar answered Jan 25 '26 04:01

Ashwini Chaudhary


because the for loop makes copies of strings.

You can use: [s[:-1] if s.endswith('\n') else s for s in aList]

Maybe this is simpler, though it will remove also whitespaces. [s.strip() for s in aList]

like image 20
Nicolas Defranoux Avatar answered Jan 25 '26 03:01

Nicolas Defranoux



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!