For loop problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

For loop problem

Anyone can explain this code: words = list(range(0,100,2)) for list in words: print(list) I know that : if code is words = list(range(0,100,2)) for x in words: print(x) program run : even number 0-98

28th Sep 2019, 4:19 AM
GroundState
GroundState - avatar
7 Answers
+ 3
list is not a function. It is a class. Python has a name hierarchy. (name can be a variable name, function name, class name or a module name) When you refer to a name, program first searches it from the local namespace. If the name is not found in the local namespace, program will then search it from the global namespace. If the name is not found in the global namespace, program will then search it from the __builtins__ name space, which includes all builtin functions and classes. If name is not found in the __builtins__ namespace program will raise an error. It is valid to use builtin functions as variable names, because local and global variable names have higher precedence than builtin names. You could have been unable to use the used builtin names, but in that case you can always use: __builtins__.name Example: print = "Hello world! 1000th time!" __builtins__.print(print) #Output: Hello world! 1000th time!
28th Sep 2019, 6:58 AM
Seb TheS
Seb TheS - avatar
+ 2
There is no reason for the first example not to work. You just can't access the list constructor anymore because you have reassigned the name "list" to an int. So this could lead to problems later on but does not make the code syntactically wrong. https://code.sololearn.com/c4b5dktspL9G/?ref=app
28th Sep 2019, 6:40 AM
Thoq!
Thoq! - avatar
+ 1
Phaiboon Jaradnaparatana list is just like any other variable. If you don't give list any value, it will refer to __builtins__.list by default.
28th Sep 2019, 7:27 AM
Seb TheS
Seb TheS - avatar
0
I think it's because `list` is Python reserved word, avoid using reserved word as variable name. That's also why your second example works unlike the first, <x> isn't a reserved word. (Edited)
28th Sep 2019, 4:33 AM
Ipang
0
My bad, it is not a reserved keyword. It's a built-in function: https://www.tutorialspoint.com/JUMP_LINK__&&__python__&&__JUMP_LINK/list_list.htm And also a data structure: https://www.tutorialspoint.com/python/python_lists.htm But now you know why we should avoid using `list` as a variable right?
28th Sep 2019, 5:19 AM
Ipang
0
The third parameter in range() indicates by which number each value should be incremented ("increase") 0 +2 2 +2 4 +2 6 +2 8 +2 10 etc.
28th Sep 2019, 6:00 AM
Trigger
Trigger - avatar
0
MY FIRST TIME RUN THIS CODE : [0,2,4,...,98] 50 TIMES BUT NOW I RESTART PROGRAM AND GOT SAME RESULT WITH 2nd CODE I dont know how it happened
28th Sep 2019, 7:14 AM
GroundState
GroundState - avatar