how to remove \n in the list

Dan Bishop danb_83 at yahoo.com
Tue Apr 15 00:08:26 EDT 2008


On Apr 14, 10:55 pm, Yves Dorfsman <y... at zioup.com> wrote:
> Gabriel Genellina wrote:
> > En Mon, 14 Apr 2008 01:41:55 -0300, reetesh nigam
> >> l=['5\n', '2\n', '7\n', '3\n', '6\n']
>
> >> how to remove \n from the given list
>
> > l is is very poor name... I'll use lines instead:
>
> > lines[:] = [line.rstrip('\n') for line in lines]
>
> When I saw the original message, I immediately thought:
>
> k = [x.strip() for x in l]
>
> What is the point of the [:] after lines ? How different is it with or
> without it ?

It causes the result to be stored in the existing list.

>>> a = [0, 1, 2, 3, 4]
>>> b = a
# "a" and "b" now refer to the same list
>>> a = [5, 6, 7]
# "a" now refers to a new list
>>> a
[5, 6, 7]
>>> b
[0, 1, 2, 3, 4]

>>> a = [0, 1, 2, 3, 4]
>>> b = a
# As before, "a" and "b" refers to the same list
>>> a[:] = [5, 6, 7]
# This replaces the elements of the list with new ones.
# "a" still refers to the same list as "b".
>>> a
[5, 6, 7]
>>> b
[5, 6, 7]



More information about the Python-list mailing list