I have a question about "in" function in Python

Thread Starter

Werapon Pat

Joined Jan 14, 2018
35
I have read about "in" function so it can check if that value is in another variables or not like "hello" in my_str or 1 in number
and it will return two values true or false. but when I use it with "for" function why it puts values from list into variables instead of return true or false like
for a in [1,2,3,4,5]:
print(a)

so I get 1,2,3,4,5 instead of true or false. how does this function actually work?
 

WBahn

Joined Mar 31, 2012
24,671
That use of the in operator is for setting up what is known as a for-each loop. You have a list of some kind and on each pass through the list the variable 'a' is set to the next element in the list. It's a very useful construct because it means that the list doesn't have to be a contiguous range and also that if the size of the list changes, the number of times through the loop automatically changes accordingly, all without having to modify the code or write any housekeeping code to do it.
 
Top