How do for loops work in python?

Click For Summary

Discussion Overview

The discussion revolves around understanding how for loops operate in Python, particularly in the context of iterating over strings. Participants explore the mechanics of string iteration, indexing, and the concept of iterables.

Discussion Character

  • Exploratory
  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant expresses confusion about how the for loop accesses array indices when iterating over a string and how Python increments the index during iteration.
  • Another participant suggests creating an empty string to accumulate characters during iteration, providing code examples for both incremental and final output.
  • A third participant challenges the initial participant's understanding, stating that changing the variable name in the loop does not affect the output and emphasizes the use of the enumerate function to access indices.
  • One participant provides a code snippet using the range function to demonstrate how to print each character of the string along with its index.
  • Another participant recommends studying Python iterators and generators for a deeper understanding of the topic.

Areas of Agreement / Disagreement

Participants express differing levels of understanding regarding the mechanics of for loops and string iteration. There is no consensus on the initial participant's misconceptions, and multiple viewpoints on how to clarify these concepts are presented.

Contextual Notes

Some participants reference specific Python functions and concepts, such as iterables and the enumerate function, but the discussion does not resolve the initial participant's confusion about indexing and iteration mechanics.

Who May Find This Useful

Individuals seeking to understand Python for loops, string manipulation, and the underlying concepts of iteration in programming may find this discussion beneficial.

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
4K
  • · 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