list 取第几个元素

时间:2023-01-03 12:16:54
#!/usr/bin/python


word=['a','b','c','d','e','f','g']


# 取第二个元素
a=word[2]
print "a is: "+a


# 取第2~3个元素
b=word[1:3]
print "b is: "
print b 


# 取前2个元素
c=word[:2]
print "c is: "
print c


# 取所有元素
d=word[0:]
print "d is: "
print d


# 同上
e=word[:2]+word[2:]
print "e is: "
print e


# 取最后一个元素
f=word[-1]
print "f is: "
print f


# 取倒数第4~3个元素
g=word[-4:-2]
print "g is: "
print g


# 取最后2个元素
h=word[-2:]
print "h is: "
print h


# 取除最后2个元素之外的元素
i=word[:-2]
print "i is: "
print i


# 取其长度
l=len(word)
print "Length of word is: "+ str(l)
print "Adds new element"


# 追加元素
word.append('h')
print word


# 追加(合并)列表
word.extend(['a', 'b'])
print word