"for i in list" making variable called i? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

"for i in list" making variable called i?

In the for loops section in the python 3 module 2 lessons, the lesson states "for i in range(5):" and in the question after it it shows i being used as a variable. Why? the lesson doesnt show why and I would like to know.

17th Jun 2018, 12:56 AM
Chance Gillcash
Chance Gillcash - avatar
3 Answers
+ 1
When you use a for loop you create a variable which will iterate through the items of an element, most likely a list. In python variable declaration is quite simple, you just give it a name and asign it to something. For example in Java you need to declare the type of the variable first(String, int, float etc). So when you create a for loop in python the syntax is as following: '' myList = [1,2,3,4,5] for i in myList: print(i)'' Here i is the variable we declared to iterate through each one of the numbers in the list called myList. You can name that variable whatever you want. For example you could have said: '' for num in myList: print(num)'' It would have been just the same. I hope that helped. :)
17th Jun 2018, 1:35 AM
Andrew Siachos
Andrew Siachos - avatar
+ 1
Thank you, and does it work like a parameter, only in the loop, or as a variable that can be used outside of it? Thanks for your help!
23rd Jun 2018, 4:42 AM
Chance Gillcash
Chance Gillcash - avatar
+ 1
Hello. Since the variable is created for the loop it can only be used within the loop. You are welcome.
23rd Jun 2018, 8:55 AM
Andrew Siachos
Andrew Siachos - avatar