Python How do for loops work in python?

AI Thread Summary
The discussion revolves around understanding how Python's for loop iterates over strings, which are treated as arrays of characters. Participants express confusion about how the loop accesses characters and how indexing works. It is clarified that when iterating over a string, Python does not explicitly increment an index; instead, it directly accesses each character in sequence. The use of the `enumerate` function is suggested for retrieving both the index and the character. Additionally, an alternative method using `range(len(str1))` is provided to explicitly show how to access each character by its index. The conversation emphasizes the importance of understanding Python's iteration mechanics and encourages further exploration of iterators and generators for deeper comprehension.
shivajikobardan
Messages
637
Reaction score
54
TL;DR Summary
how for loops work in python
Code:
str1="hello"

for stringElement in str1:
    print("str1","=",stringElement)

1638113476732.png


Strings are arrays in python and they are represented like this.

Now I want to understand how the for loop is working here.

My dry run-:
Code:
 for h in str1
     print h

Code:
 for e in str1
     print e
and so on till o...

My confusions-:

This is what I have read about python for loop from a book called python power.

https://i.stack.imgur.com/qApVt.png

My confusion is that-:

1) How can I see array index 0 when h is being printed
2) How does python knows to increment array index by 1 after the end of each for loop? I heard strings are iterables in python. But I am not very clear what do they really mean here in this case. So some guidance will be really valuable.
 
Last edited:
Technology news on Phys.org
I think what you want to do is create an empty string at the beginning of the for loop and add to the empty string with each iteration

Code:
str1 = "hello"
str2 = ""

for str_element in str1:
    str2 = str2 + str_element
    print(str2)

Or if you want to just create the entirety of the new string (a copy) and then print it all at the end (instead of printing at the end of each iteration) you just change the indent

Code:
str1 = "hello"
str2 = ""

for str_element in str1:
    str2 = str2 + str_element

print(str2)

Did I understand your question correctly?
 
I think you have big misconceptions.
shivajikobardan said:
My dry run-:
Code:
 for h in str1
     print h

Code:
 for e in str1
     print e
and so on till o...
Have you tried to run these codes? both are exactly equal and will produce the exact same result and the same all others 'till o'. You are just changing the variable, but there's no difference in the result.

shivajikobardan said:
My confusion is that-:

1) How can I see array index 0 when h is being printed
2) How does python knows to increment array index by 1 after the end of each for loop? I heard strings are iterables in python. But I am not very clear what do they really mean here in this case. So some guidance will be really valuable.
For 1) I think the question arises from your misconceptions, you can obtain the index of the iteration using the enumerate function.

For 2), python doesn't know to increment any index by 1, this is not what is doing. It is iterating over all the elements of the string (which are length 1 strings), so the only thing Python needs to know is what is the current element and what will be the next.
 
  • Like
Likes shivajikobardan and PhDeezNutz
Is this what you are looking for:

Python:
str1="hello"

for index in range(len(str1)):
    print("str1[",index,"] = ",str1[index])

Which should give:

Code:
str1[ 0 ] =  h
str1[ 1 ] =  e
str1[ 2 ] =  l
str1[ 3 ] =  l
str1[ 4 ] =  o
 
  • Like
Likes shivajikobardan, jedishrfu and anorlunda
jack action said:
Is this what you are looking for:

Python:
str1="hello"

for index in range(len(str1)):
    print("str1[",index,"] = ",str1[index])

Which should give:

Code:
str1[ 0 ] =  h
str1[ 1 ] =  e
str1[ 2 ] =  l
str1[ 3 ] =  l
str1[ 4 ] =  o
exactly. thanks...LOTS OF THANKS. This was in my book but index=0 was done there so I got confused.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
hi; i purchased 3 of these, AZDelivery 3 x AZ-MEGA2560-Board Bundle with Prototype Shield and each is reporting the error message below. I have triple checked every aspect of the set up and all seems in order, cable devices port, board reburn bootloader et al . I have substituted an arduino uno and it works fine; could you help please Thanks Martyn 'avrdude: ser_open(): can't set com-state for "\\.\COM3"avrdude: ser_drain(): read error: The handle is invalid.avrdude: ser_send(): write...

Similar threads

Back
Top