2

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.

2
  • 2
    q = [start] means 'make a list called q, and put the variable start in as the first element'. while q: means 'repeat the following indented block until it is empty' (because lists coerce to boolean True while non-empty and False while empty). Is the indentation as you are showing here though? If so, it won't run correctly. Commented Oct 16, 2016 at 13:11
  • 1
    This is just a part the code.So my assumption was correct.Thanks for the comment you can write it as an answer, I will accept it. Commented Oct 16, 2016 at 13:14

1 Answer 1

3

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'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.