Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python While Loop Syntax

class Solution: 
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

Hello, I am having some difficulties understanding the above while loop, AFAIK you need to have a condition with a while loop, so:

while (stuff) == True:

But the above code has:

while current:

Is this the same as:

while current == head:

Thanks

like image 631
MathsIsHard Avatar asked Mar 04 '26 07:03

MathsIsHard


1 Answers

The while current: syntax literally means while bool(current) == True:. The value will be converted to bool first and than compared to True. In python everyting converted to bool is True unless it's None, False, zero or an empty collection.

See the truth value testing section for reference.

like image 121
Mariusz Jamro Avatar answered Mar 05 '26 20:03

Mariusz Jamro