0

the following is a part of C code for singly linked list:

for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next);

How do I convert this for loop in C to for loop in Python?

2
  • 2
    Don't put all your logic in the for statement. It makes the code hard to understand. Commented Aug 11, 2021 at 18:59
  • If you provide a complete, reproducible example, we can help you convert it to python. As it is we have to make some assumptions about the data structures that you've used. Commented Aug 11, 2021 at 19:02

1 Answer 1

2

In C

for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next);

is equivalent to

tptr = start;
while (tptr != NULL && tptr->data < newnode->data) {
  prev = tptr;
  tptr = tptr->next;
}

A C-style for loop is rather a while loop. Expressing it in Python with a for construct would be certainly possible (e.g., writing a for loop that runs forever and breaking out if the condition is not met), but it would not be best practice.

In Python, I would recommend to express your example with a while loop (unless it is a simple for-loop like iterating over the numbers 0 to n).

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.