Python For Loop List Interesting Result

前端 未结 4 1921
执念已碎
执念已碎 2021-01-25 07:42
a = [0,1,2,3,4,5]
for b in a:
  print \":\"+str(b)
  a.pop(0)

Thinking that this would work in order going through the entire list and all its items I

4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 08:17

    If you want to use .pop() in a loop, a common idiom is to use it with while:

    a = [0,1,2,3,4,5]
    while a:
      print ":{}".format(a.pop(0))
    

    Or, if you want the printed pattern you have there:

    a = [0,1,2,3,4,5]
    while a:
        print ":{}\n{}".format(a[0],a.pop(0))
    

    prints

    :0
    0
    :1
    1
    :2
    2
    :3
    3
    :4
    4
    :5
    5
    

提交回复
热议问题