+ 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

8th Feb 2018, 9:07 PM
mohamadjavad
mohamadjavad - avatar
4 Answers
+ 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.
12th Feb 2018, 8:01 PM
David Carroll
David Carroll - avatar
+ 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)
12th Feb 2018, 6:37 PM
Shubham Mehta
Shubham Mehta - avatar
+ 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.
8th Feb 2018, 9:26 PM
Toni Isotalo
Toni Isotalo - avatar
+ 1
thank you
9th Feb 2018, 8:42 AM
mohamadjavad
mohamadjavad - avatar