+ 9
Why it's "i for i"??
a=[ i for i in range(20) if i%3==0] print(a)
7 ответов
+ 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', ...]
+ 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.
+ 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
+ 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
+ 3
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥
Aren't these all are same i.e.
List comprehension