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

MathsIsHard
  • 277
  • 3
  • 9
  • 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](http://stackoverflow.com/users/342473/mariusz-jamro)'s [answer](http://stackoverflow.com/a/38230275/2465194) below explains. – rtmh Jul 06 '16 at 17:45

3 Answers3

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.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
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)

Faibbus
  • 1,115
  • 10
  • 18
  • 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:` – cat Jul 06 '16 at 17:38
  • There are other falsy values in Python than `None` so this is incorrect. – cat Jul 06 '16 at 17:39
  • 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 – Faibbus Jul 06 '16 at 18:10
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:
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • There are other falsy values in Python than None so this is incorrect. – cat Jul 06 '16 at 17:40
  • I said "I assume that value is None" because that's the typical way to implement something like this. – Barmar Jul 06 '16 at 17:41