+ 9

Why it's "i for i"??

a=[ i for i in range(20) if i%3==0] print(a)

2nd Jul 2020, 7:35 AM
Arctic Fox
Arctic Fox - avatar
7 Respuestas
+ 4
I think the question is, what this first "i" means in [i for i in range(...)...]. This first "i" is the so called "Output Expression", that will be stored to the new list. For our case: "i" will be used as it is and stored to the new list. But you can also do a mathematical operation with "i", which means that each value generated by the range() function can be modified by this Output Expression. new_list = [i * 2 for i in range(5)]. in this case each value from range() will be multiplied by 2 and then stored in the new list. You can also use builtin-functions or user defined functions to modify the input. Let's say we need numbers from 0 to 5 as strings. This can be done with: new_list = [str(i) for i in range(5)]. The output will be a new list like ['0', '1', ...]
2nd Jul 2020, 11:51 AM
Lothar
Lothar - avatar
+ 3
List Comprehension is one-line for loop https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2454/ You can use [ j for j....] or [ k for k....] or [ haha for haha...] any temporary variable name are ok.
2nd Jul 2020, 7:39 AM
Gordon
Gordon - avatar
+ 3
Gordon I mean why it's used. It can be for i in range but trying to do so results in error. Commonly it's not used other than list comprehension
2nd Jul 2020, 7:53 AM
Arctic Fox
Arctic Fox - avatar
+ 3
Simplified version is this: a = [ ] for i in range(20): a.append(i) Therefore the i for i means add or append the value of i to the list for i in range(20). Also, there's this amazing tutorial by HonFu on list comprehensions. Check it out https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
2nd Jul 2020, 8:32 AM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 3
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 Aren't these all are same i.e. List comprehension
2nd Jul 2020, 8:32 AM
Arctic Fox
Arctic Fox - avatar