Slicing every element of a list

Thomas Lotze thomas at thomas-lotze.de
Tue Jul 12 16:27:42 EDT 2005


Alex Dempsey wrote:

> for line in lines:
>     line = line[1:-5]
>     line = line.split('\"\t\"')
> 
> This went without returning any errors, but nothing was sliced or split.
> Next I tried:
> 
> for i in range(len(lines)):
>     lines[i] = lines[i][1:-5]
>     lines[i] = lines[i].split('\"\t\"')
> 
> This of course worked, but why didn't the first one work.

Because when assigning to line the second time, you just make the
identifier reference a new object, you don't touch the list. This is how
one might do it without ranging over the length of the list and having
to get the lines out by element access:

for i, line in enumerate(lines):
    line = line[1:-5]
    lines[i] = line.split('\"\t\"')

Probably there are even better ways, this is just off the top of my
head.

> Further why
> didn't the first one return an error?

Because you didn't make any. You just discarded your results; why should
anyone stop you from burning cycles? *g

-- 
Thomas





More information about the Python-list mailing list