Can some one please help me to understand the difference in output of below code snippets. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can some one please help me to understand the difference in output of below code snippets.

l=[1,'sa',3.5] for i in l : print(l[i]) l=[1,'sa',3.5] for i in l : print([i])

15th Mar 2020, 6:35 PM
kishore sai anil
2 Answers
+ 6
This code does not work. (syntax error in for loop, and index error in print). What it should do is: There is a list "l" that contains 3 elements: an int, a string and a float. Then a for loop is going to run, getting each of the elements of the list, and trying to use this as an index for "l". As index can only be integers, the code fails with the string "sa" and the float 3.5. l=[1,'sa',3.5] for i in l : print(l[i]) This code is working (but also syntax error in for loop). The procedure is like in the previous sample, except that the elements are not used as index, but just as the value they represent. print([]) creates a list as output for each element. l=[1,'sa',3.5] for i in l : print([i])
15th Mar 2020, 7:00 PM
Lothar
Lothar - avatar
+ 1
Both of them wouldn't work, since your for loop is incorrect. It should be: for i in 1: instead of for in l: However, assuming that you corrected that, the first one would return an error, something like "list indices cannot be string" or "list indices cannot be float", except for the first value(1), since you are looping through each item, meaning i is equal to each item in the list. The second one would run perfectly fine, and return each value in a list, E.G [1].
15th Mar 2020, 6:57 PM
Jianmin Chen
Jianmin Chen - avatar