Login Register






for loop question in python filter_list
Author
Message
for loop question in python #1
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

Reply

RE: for loop question in python #2
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.
My Blog: http://www.procurity.wordpress.com
Donations: 1HLjiSbnWMpeQU46eUVCrYdbkrtduX7snG

Reply

RE: for loop question in python #3
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.

Reply

RE: for loop question in python #4
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:
MASTERING OTHERS IS STRENGTH, MASTERING YOURSELF IS TRUE POWER.

[Image: qJweLN6.jpg]

Reply