2
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

1
  • You seem to be confused about the meaning of the statement above the while loop. It has nothing to do with the loop or it's conditional. Instead, it is copying the variable head to the variable current. Current is then converted to a boolean and checked for it's 'truthiness' as Mariusz Jamro's answer below explains. Commented Jul 6, 2016 at 17:45

3 Answers 3

10

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.

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

1 Comment

Thank you, it makes sense now
0

Your loop can be considered as

while current is not None:

because the parser will try to interpret current as a boolean (and None, empty list/tuple/dict/string and 0 evaluate to False)

3 Comments

No, it is more like while current is not None and current is not False and current is not [] and current is not {} and current is not 0 and current is not "":. Actually, it's while bool(current) == True:
There are other falsy values in Python than None so this is incorrect.
I've edited my answer to be more complete... but current.next is most likely to return None if there is no next element. Moreover, while bool(current) is enough, no need to check for equality with True
0

The value of the variable current is the condition. If it's truthy, the loop continues, if it's falsy the loop stops. The expectation is that in the last element in the linked list, next will contain a falsy value. I assume that value is None, and in that case the loop is equivalent to:

while Current is not None:

If, instead, the linked list uses false as the end marker, it's equivalent to:

while Current != false:

2 Comments

There are other falsy values in Python than None so this is incorrect.
I said "I assume that value is None" because that's the typical way to implement something like this.

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.