|  | 
 
| 
guests = ['a','b','c']
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  print (guests)
 print ("hello "+guests[0]+" welcome")
 guests[1]="d"
 print (guests)
 # [a d c]
 print ("b can not attend.")
 guests.append('e')
 #[a d c e]
 print(guests)
 print("welcome "+guests[0]+" attend my this party!")
 print("welcome "+guests[1]+" attend my this party!")
 print("welcome "+guests[2]+" attend my this party!")
 print("welcome "+guests[3]+" attend my this party!")
 print("i find a big table,so we change the place")
 guests.insert(0,'f')
 #[f a d c e]
 guests.insert(2,'g')
 #[f a g d c e]
 print(guests)
 print('i am so sorry ,i only can invite two.')
 first = guests.pop(0)
 print ("sorry "+guests.pop(0))
 #sorry f
 second = guests.pop(1)
 print ("sorry "+guests.pop(1))
 #sorry a
 third = guests.pop(2)
 print ("sorry "+guests.pop(2))
 #sorry g
 forth = guests.pop(3)
 print ("sorry "+guests.pop(3))
 #sorry d
 print(guests)
 print(guests[0]+" welcome")
 #c welcome
 print(guests[1]+" welcome")
 #e welcome
 #最后我想把列表清空
 del guests[0]
 del guests[1]
 print(guests)
 
 
 说明一下 #后面的是我预想的结果 但是一运行就出问题了
 显示这个     跟我预想的完全不同
 ['a', 'b', 'c']
 hello a welcome
 ['a', 'd', 'c']
 b can not attend.
 ['a', 'd', 'c', 'e']
 welcome a attend my this party!
 welcome d attend my this party!
 welcome c attend my this party!
 welcome e attend my this party!
 i find a big table,so we change the place
 ['f', 'a', 'g', 'd', 'c', 'e']
 i am so sorry ,i only can invite two.
 sorry a
 sorry c
 Traceback (most recent call last):
 File "C:/Users/hp/Desktop/comp1002/自学/invitation.py", line 28, in <module>
 third = guests.pop(2)
 IndexError: pop index out of range
 
因为你pop了两遍。first一遍pop,打印一遍pop。 正确的应该是 
并且这种pop完了之后,列表的下标完全都变了,5个元素变成4个元素,原来的1下标变成了0下标,导致你后面index超过列表长度了。
 | 
 |