DEV Community

HHMathewChan
HHMathewChan

Posted on • Updated on

Python Daily exercise 1: Generate a list of even number

Today, I just continue to do exercise on PYnative

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]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

print(list(range(4, 30, 2)))
Enter fullscreen mode Exit fullscreen mode

My reflection

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

Top comments (0)