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
2010-10-25 02:16:37
+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
2010-10-25 02:18:35
"del in list": look into it: L = range(5); del L[2]; assert L == [0, 1, 3, 4]
Ned Batchelder
2010-10-25 02:26:08
@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
2010-10-25 02:26:53
@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
2010-10-25 02:31:43
@Ned gotit. Not used to this syntax.
MovieYoda
2010-10-25 02:33:15
@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
2010-10-25 03:09:36
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
2010-10-25 08:10:51