How do for loops work in python?

Click For Summary
SUMMARY

This discussion focuses on the mechanics of for loops in Python, particularly how they iterate over strings, which are treated as arrays of characters. The user expressed confusion regarding the visibility of array indices during iteration and how Python manages the incrementing of these indices. Key insights include the use of the enumerate function to access indices and the clarification that Python iterates over elements rather than managing an explicit index increment. The provided examples demonstrate both character-by-character iteration and index-based access.

PREREQUISITES
  • Understanding of Python syntax and basic programming concepts.
  • Familiarity with Python strings and their properties as iterable objects.
  • Knowledge of the enumerate function in Python.
  • Basic understanding of Python's iteration mechanisms, including iterators and generators.
NEXT STEPS
  • Learn how to use the enumerate function in Python for indexed iteration.
  • Study Python iterators and generators to deepen understanding of iteration.
  • Explore string manipulation techniques in Python for efficient data handling.
  • Review Python's official documentation on loops and control flow for advanced usage.
USEFUL FOR

Beginner to intermediate Python developers, educators teaching programming concepts, and anyone looking to enhance their understanding of string iteration in Python.

shivajikobardan
Messages
637
Reaction score
54
TL;DR
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   Reactions: 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   Reactions: 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.
 

Similar threads

  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 16 ·
Replies
16
Views
3K
Replies
55
Views
7K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K