views:

94

answers:

4

I'm having some trouble with a couple of hmwk questions and i can't find th answer- How would you write an expression that removes the first or last element of a list? i.e. One of my questions reads "Given a list named 'alist' , write an expression that removes the last element of 'alist'"

+2  A: 

Have you looked at this? http://docs.python.org/tutorial/datastructures.html Particularly at pop([i])? Your assignment sounds like a standard question in functional programming. Are you supposed to use lambdas?

Tronic
+1  A: 

I'm pretty sure its as simple as "alist.pop()"

Marm0t
+1  A: 

Here's how you do it in Python -

x = range(10) #creaete list
no_first = x[1:]
no_last  = x[:-1]
no_first_last = x[1:-1]

UPDATE: del in list? Never heard of that. Do you mean pop?

MovieYoda
"del in list": look into it: L = range(5); del L[2]; assert L == [0, 1, 3, 4]
Ned Batchelder
@movieyoda: -1 Your answer doesn't remove the element(s) from x -- x is untouched, and it's not an expression, it's an assignment statement. BTW, what does "del in list?" mean??
John Machin
@John he never mentioned that I need to work with one `list` only! Also if you are that bent on saving space, then reassign to new list after modification. `x = x[1:-1]`
MovieYoda
@Ned gotit. Not used to this syntax.
MovieYoda
@movieyoda: requirement is "write an expression that removes the last element of 'alist'". Yours doesn't. It copies parts of the original list and then rebinds the name to the copy. "after modification"?? Of what?? No modification has taken place, that's the whole point.
John Machin
A: 
>>> a=[1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> del a[0]  # delete the first element
>>> a
[2, 3, 4]
>>> del a[-1] # delete the last element
>>> a
[2, 3]

It's also possible to delete them both at once

>>> 
>>> a=[1,2,3,4,5,6]
>>> del a[::len(a)-1]
>>> a
[2, 3, 4, 5]
gnibbler