Is there an easier way to express this list slicing?
john106henry at hotmail.com
Thu Nov 30 20:39:41 CET 2006
mdsteele at gmail.com wrote:
> 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:]
Dude! Why didn't I think of that (tunnel vision).
> > 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
> 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)
More information about the Python-list