Generating a list of EVEN numbers in Python

前端 未结 14 608
轻奢々
轻奢々 2021-01-17 15:48

Basically I need help in generating even numbers from a list that I have created in Python:

[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597         


        
14条回答
  •  清酒与你
    2021-01-17 16:20

    You can use list comprehension to generate a new list that contains only the even members from your original list.

    data = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
    

    then:

    new_data = [i for i in data if not i%2]
    

    yields

    [2, 8, 34, 144]
    

    Or alternatively use a generator expression if you don't need all of the numbers at once:

    new_data = (i for i in data if not i%2)
    

    The values then would be availabe as needed, for instance if you used a for loop:

    e.g.,

    for val in new_data:
       print val
    

    The advantage of the generator expression is that the whole list is not generated and stored in memory at once, but values are generated as you need them which makes less demand on memory. There are other important differences you might want to read up on at some point if you are interested.

提交回复
热议问题