+ 1

Can anyone plz explain me about working of FOR LOOP in PYTHON with an example?

I think logical working of for loop in Python is different from the logic of for loop in other languages such as c,c++,java...so I am not able to understand correctly in case of Python.

29th Mar 2017, 3:37 AM
SHRIDHAR JOSHI
4 Réponses
+ 17
A for loop is mainly for using a standard variable as you iterate through an iterable, such as a list/dictionary/tuple/etc., and do something with the values contained within, while utilizing that variable. In the following, a list is created, then the values are iterated through in a for loop using "value" with each iteration as a variable for the new increment within the iterable: list_a = [0,1,2,3,4,5,6,7,8,9] for value in list_a: print(value) or the for loop as a list comprehension: [print(value) for value in range(0,9)] Remember the length of the iterable is the range of the loop, unless there is a conditional if. Also, the python documentation is very extensive when needing in depth explanations.
29th Mar 2017, 3:45 AM
David Hutto
David Hutto - avatar
+ 3
You are right, there is a difference between for loops in Python and for example C. In C you define a halting condition and an iteration step, while in Python you iterate over the items of any iterable object. The Python tutorial and language reference do a great job at explaining what that means without leaving any guesswork: https://docs.python.org/3/tutorial/controlflow.html#for-statements https://docs.python.org/3/reference/compound_stmts.html#for Iterable and iterator have very precise meanings, to be found here: https://docs.python.org/3/glossary.html
29th Mar 2017, 5:09 AM
Tob
Tob - avatar
+ 1
for i in range(10): i is a variable. since we are for looping thru a range of 10, it represents whatever number the loop is on. for i in range(10): run #1 .. i=0 run #2 .. i=1 if we had a list we wanted to iterate thru, i is each item in the list. like this mylist=["a", "b", "c"] for i in mylist: run #1 .. i="a" run #2 .. i="b" in my personal opinion, Python for loop is easier than Java for i in range(10): vs for(int i=0; i <10; i++){ } and for i in myList: vs for(String letter: myList){ }
29th Mar 2017, 4:06 AM
LordHill
LordHill - avatar
2nd May 2019, 5:43 AM
geraldmuller