开发者

A question about lists in Python

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 开发者_StackOverflow社区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'"


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?


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


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?


>>> 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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜