Sinisterly
for loop question in python - Printable Version

+- Sinisterly (https://sinister.li)
+-- Forum: Coding (https://sinister.li/Forum-Coding)
+--- Forum: Python (https://sinister.li/Forum-Python)
+--- Thread: for loop question in python (/Thread-for-loop-question-in-python)



for loop question in python - Cosh - 06-12-2014

So I'm currently reading learning python and doing codeacademy for teaching myself python. I have taken a java courses in college, but I'm having a hard time exactly understanding the for loop.

Basically I know in java it's setup like int x; x<0; i++ so i can understand what's going on, but in python I don't fully understand why I'm adding the for x in whatever. Can someone explain it to me in simple wording? sorry if my post makes no sense i'm just getting a little frustrated that I don't fully understand the for loop


RE: for loop question in python - Ex094 - 06-12-2014

Suppose you have a list of 5 items:

Code:
list = ['HC', 'Blue', 'Doge', 'Ark', 'Geo']

Now when you do this:

Code:
for items in list

Which is actually the for loop syntax for python, It means that LOOP for the NUMBER OF ITEMS inside the variable list. Since there are 5 items, so it will loop 5 times.

Hence you do not need a looping variable and a limit like in C++, Java etc, Python takes care of that for you.


RE: for loop question in python - phiber - 06-17-2014

for loop can also be used in range() function like,

Code:
for i in range(1,10): #your code print i

this loop will loop through 1 - 9 with your variable i holding the value.


RE: for loop question in python - L0aD1nG - 06-19-2014

On python programming language there is a built-in function called iter().

I take an iterable object and returns it's iteration object.

for loop is designed to be able to work that way.

So you can iter over a list without indexing and getting x assigned by the items of the list.

Try that out you will get it.

Code:
x = [1,2,3,4] iter_x = iter(x) for i in iter_x: print(i)
But for loop automation on itering over the objects given allows you to avoid the iter() and let for loop handle it.
Code:
x = [1,2,3,4] for i in x: print(i)
You see exactly the same outputs.
Trying to print the iter_x from first code will return a listiterator object thats what by auto for uses to make the loop...if you want to still use indexes for some reason you can use this too
Code:
x = [1,2,3,4] for i in range(4): print("Current Index : %s "%i) print("Current Item : {} ".format(x[i]))

I hope that helped...i am always available on helping for python questions count me :epic: