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'"
-
Please add "Homework" tag to this questionmshsayem– mshsayem2010-10-25 02:13:47 +00:00Commented Oct 25, 2010 at 2:13
-
This might help: diveintopython.org/native_data_types/lists.htmlsje397– sje3972010-10-25 02:15:08 +00:00Commented Oct 25, 2010 at 2:15
-
or docs.python.org/tutorial/datastructures.htmlCoding District– Coding District2010-10-25 02:17:52 +00:00Commented Oct 25, 2010 at 2:17
Add a comment
|
4 Answers
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?
Comments
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?
5 Comments
Ned Batchelder
"del in list": look into it: L = range(5); del L[2]; assert L == [0, 1, 3, 4]
John Machin
-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??
Srikar Appalaraju
@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]Srikar Appalaraju
@Ned gotit. Not used to this syntax.
John Machin
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.