educative.io

For loops in Python

A reader asked the following question:

I’ve noticed that you use range objects with for loops to iterate over strings. Why don’t you use a regular for loop instead? ie. why not do this: for c in input_str: stack.push(c) instead of: for i in range(len(input_str): stack.push(input_str[i])

First of all, in response to “Why don’t you use a regular for loop instead?”, I’d say that it is not correct to refer to your version as a “regular for loop” Both implementations involve the “regular for loop” structure. Secondly, you can use the “for c in input_str”. Both implementations, in this case, will yield identical results. If you prefer the latter implementation, that’s fine too. Hope this helps!

Best Regards,
Alina Fatima | Developer Advocate

1 Like

I just wanted to point out that using

for char in string:
    stack.push(char)

Is faster, more efficient, and looks cleaner than using a range object:

for char_index in range(len(string)):
    stack.push(string[char_index])

I wanted to use general terms when I said “regular for loop” because the majority of experienced Python programmers use for char in string to iterate over a string instead of using a range object. I’m sorry for being too vague with my words, it is just common practice to iterate over the string without the need of a range object and I assumed you would understand what I meant. My apologies.

Thank you for your response :slight_smile: @Alina_Fatima

1 Like