+ 5
What's this code means?
a=int(input('enter a num')) b=[x for x in range (2,a) if a%x==0] #this
4 ответов
+ 5
@Shubham... I really like your approach to break it apart in this format.
Expanding on this, I would clarify this further as:
new_list = [ (expression: to append using current value) for (the current value) in (collection) (where: some condition is true) ]
This is equivalent to the following:
new_list = []
for (the current value) in (collection):
if (some condition is true):
new_list.append(expression: using current value)
- The (expression) part could be the current value or an expression that modifies the current value.
- The (where) part is optional and could be zero or more if statements or for loops.
Your version is nicely condensed. I just wanted to expand with additional clarifications.
+ 4
here LIST COMPREHENSION is used with list 'b' whose expression is as below:
b = [ (expression) for (value) in (collection)]
this is epuivalent to a for loop as if :
b = []
for (value) in (collection) :
b.append(expression)
+ 1
Let's look at it this way
b = [x for x in range (2,10) if 10%x==0]
the range function returns a list like this [2, 3, 4, 5, 6, 7, 8, 9]
The "for" loop goes through the whole list number by number and stores it to the x variable
"for" loop goes 8 times (from 2 to 9) and if 10 divided with the number goes even it adds it to the list.
result will be b = [2, 5]
But in your code the number will be given by the user.
+ 1
thank you