Reverse Nodes in k-Group in Python

class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        # Helper function to reverse a part of the linked list.
        def reverseLinkedList(start, end):
            prev, curr = None, start
            while curr != end:
                next_temp =
       = prev
                prev = curr
                curr = next_temp
            return prev

        # Dummy node to handle edge cases easily.
        dummy = ListNode(0) = head
        prev_group_end = dummy

        while True:
            kth_node = prev_group_end
            # Find the kth node from the current position.
            for _ in range(k):
                kth_node =
                if not kth_node:
                    return  # Return the new head of the list.

            # Mark the end of the next group.
            next_group_start =

            # Reverse the current group.
            new_group_start = reverseLinkedList(, next_group_start)

            # Connect the reversed group with the rest of the list.
            temp =
   = new_group_start
            prev_group_end = temp

            # Set the next node for traversal.
   = next_group_start