[Tutor] assigning portions of list to another

Daniel Yoo dyoo@CSUA.Berkeley.EDU
Mon, 16 Sep 2002 10:38:51 -0700 (PDT)


On Mon, 16 Sep 2002, Joseph Paish wrote:

> i am trying to copy certain elements from a list into individual
> variables without writing one line of code for each assignment of value
> to variable.  i am missing something that is probably very obvious.  i
> have tried numerous different combinations of things, and this is the
> latest:
>
> this is what i have so far:
>
> >>> first_record = [1, 2, 3]
> >>> second_rec = [4, 5, 6]
> >>> merged_rec = first_record + second_rec
> >>> print merged_rec
> [1, 2, 3, 4, 5, 6]
>
> (okay so far)
>
> (now to assign certain elements to variable names)
>
> >>> nbr1, nbr2, nbr3 = merged_rec[0, 3, 4]
> Traceback (innermost last):
>   File "<pyshell#15>", line 1, in ?
>     nbr1, nbr2, nbr3 = merged_rec[0, 3, 4]
> TypeError: sequence index must be integer


Unfortunately, Python doesn't support the exact same array slicing
mechanisms that a language like Perl does.  To pull out those three
elements, we can do something like this:

###
nbr1, nbr2, nbr3 = merged_rec[0], merged_rec[3], merged_rec[4]
###

but this is a little... well... dull!  *grin*



We can improve this by writing a function that slices the list for us:

###
def slice(sequence, indices):
    """Returns a sequence 'slice', given a list of indices."""
    portions = []
    for i in indices:
        portions.append(sequence[i])
    return portions
###


Once we have this, we can use this slice() function like this:

###
>>> merged_rec = [1, 2, 3, 4, 5, 6]
>>> nbr1, nbr2, nbr3 = slice(merged_rec, [0, 3, 4])
>>> nbr1
1
>>> nbr2
4
>>> nbr3
5
>>> slice("this is a test of the emergency broadcast system",
...       [0, 2, 7, 15])
['t', 'i', ' ', 'o']
###


The last example shows that this slice()ing should work on any
sequence-like object, including strings.


I hope this helps!