Is there an easier way to express this list slicing?

mdsteele at gmail.com mdsteele at gmail.com
Thu Nov 30 20:22:26 CET 2006


John Henry wrote:
> Can I say something to the effect of:
>
> (a,b,c[0:2],d[0:5])=a_list    # Obviously this won't work

Your best bet is probably:

x = [...some list...]
a,b,c,d = x[:1],x[1:2],x[2:5],x[5:]

> I am asking this because I have a section of code that contains *lots*
> of things like this.  It makes the code very unreadable.

Of course, if you're always slicing up lists the same way (say, into
1,1,3,5 element sections) then you could improve readability by writing
a function that takes the list and returns a tuple of the pieces, such
as:

def slice_list(x):
    return x[:1],x[1:2],x[2:5],x[5:]

a,b,c,d = slice_list(first_list)
e,f,g,h = slice_list(second_list)

-Matt




More information about the Python-list mailing list