аватар question@mail.ru · 01.01.1970 03:00

How does the code work [I for i in Range (51) if I % 2 == 0]?

  Evens_to_50 = [I  for  i  in   range  ( 51 )  if  i %  2  ==  0 ]   Print  Evens_to_50    

This code generates a list of even numbers up to fifty. But I, as new in programming, do not understand some points -:

  1. Why the generation occurs in square brackets, they are usually used when working with indices
  2. What does the first i do for ? Why after range (51) there are no colonies and transfer to a new line with tabulation?
  3. Where else can square brackets use? for write? What are the rules in them?
аватар answer@mail.ru · 01.01.1970 03:00

This design is called "generator". This is a line in one line to create a list (array) filled with values. There are no colonies precisely because it is not a cycle of for , but a generator. Let's analyze in detail:

  [i  for  i  in   range  ( 51 )  if  i %  2  ==  0 ]  

or in a more general form:

  [expr (variable)  for  variable  in  iterable  if  Condition (Variable)]     

here:

  • iterable & mdash; A certain object from which you can receive values ​​one by one (until it ends). List, motorcade or, for example, dictionary keys. From here the values ​​are taken by the variable variable . Alteate operations are called "" iterations "", and the above object & mdash; .

    the expression range (51) retus a list of natural numbers from 0 to 50 inclusive. We are sorting out.

  • variable (arbitrary name) & mdash; Just a variable, alteately accepting all values ​​from iterable . It works in the same way as a meter in the cycle.
  • Expr (Variable) & mdash; Any function that retus value. She can take an argument of variable , maybe anything else, can not accept anything at all. It is clear that i retus simply the value of i unchanged. The values ​​retued by this function become elements of the generated list. Other examples:

    • [I ** 2 for i in Range (51)] & ndash; Squares of numbers
    • [0 for i in Range (51)] & ndash; & nbsp; just fill out zero
  • control (Variable) & mdash; An optional condition. If it is present, then the resulting list will include only those values ​​for which control (Variable) == True . You can write one if , but inside it can be an arbitrarily complicated expression, i.e. if a (i) and b (i) or c (i) ...

    In this case, those numbers that are multiplied by two (i.e., even).

Latest

Similar