I am a beginner to python so this might be easy but I am not sure of what the following code means.
q=[start]
while q:
Does this mean when there is at least one element in the list q execute it and q becomes false when it is empty? Edit:I cannot execute it at the moment and I need to find it quickly.
The line q = [start]
means create a variable called q
, and assign the value [start]
to it . In this case, it will create a list with one element: the value of the variable start
. It's the exact same syntax as q = [1, 2]
, but it uses a variable instead of a constant value.
After this, the line while q:
is a use (or abuse) of Python's type conversion system. While loops require a boolean condition to know whether they should repeat, so your code is equivalent to while bool(q):
. To understand how this works, let's examine the possible cases:
bool([1]) == True # This applies for any non-empty list
bool([]) == False # This applies to any empty list
Therefore, the meaning of while q:
is actually 'while q
is non-empty'.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.