Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 views
in Technique[技术] by (71.8m points)

How does a list in a for loop work in Python?

So I have this code:

def function(b):
   a = []
   for i in range(0,len(b),2)
       a.append(b[i])
   return a

def main():
   a = [0,1,2,3,4,5,6,7,8,9,10,11]
   for i in[51,"a", 3.2]
      a = function(a)
   print a
main()

I don't understand how the for loop works with the list [51, "a", 3.2], and why with that list it prints [0, 8], but with the list[51, "a"] prints [0,4,8].

question from:https://stackoverflow.com/questions/65885110/how-does-a-list-in-a-for-loop-work-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

essentially every time you call the function it will return you only the elements form the even indexes.

you then store them back into a So each time your calling the function and storing the result your halfing the list storing only those from the even indexes. That values in your list [52, "a", 3.2] are only essentially tellin ghow many times to call the function.

when you call it 3 times, you will have less results than when you call it 2 times. you can see this if you put the print in side the loop

def function(b):
   a = []
   for i in range(0,len(b),2):
       a.append(b[i])
   return a

def main():
   a = [0,1,2,3,4,5,6,7,8,9,10,11]
   for i in[51,"a", 3.2]:
      a = function(a)
      print(a)
       
main()

OUTPUT

[0, 2, 4, 6, 8, 10]
[0, 4, 8]
[0, 8]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...