Python Beginner Exercise 1: Generate An Even Number List

Table of Contents

original post on https://dev.to/mathewchan/daily-exercise-194b/

Question

The question is to generate a list of all even number between 4 to 30.
The expected output is:

[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

Solution

At first, my solution is using a for loop to produce the list as follow:

list1 = []  
for number in range(4,30):  
    if not number % 2:  
        list1.append(number)  

print(list1)

But the recommended is really simple, just use the list(), which is:

print(list(range(4, 30, 2)))

My reflection

Now I learn a new function, should handle the same problem easily next time.

Credit

Exercise from PYnative

Leave a Reply