I'm starting with python and practicing a code to print even numbers out of a list.
Sample List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Code:
def p_even(lst):
for num in lst:
if num %2 == 0:
return num
I'm expecting the even numbers from the list [2,4,6,8], but is just givin me the number 2.
Yes, that code will return the first even number it finds, ceasing processing of the list when it does.
If you want all the even numbers, you can just use(a):
def p_even(lst):
# _____Construct new list_____
# / \
return [x for x in lst if x % 2 == 0]
# \____________/ \___________/
# from these elements that meet this condition
(the comments are there for explanation only, they're probably not needed in any actual code you write).
This is called list comprehension in Python and is a powerful way (in this case) to create another list from your list by filtering certain elements.
To print the elements, you can either just print the returned list itself (the first line below) or print each element (the for
loop below):
print(p_even(range(20))
for itm in p_even(range(20)):
print(itm)
(a) You can use an explicit loop for this, such as:
def p_even(lst):
even_lst = []
for itm in lst:
if itm % 2 == 0:
even_lst.append(itm)
But it's not really considered "pythonic". Python provides very expressive (and concise) ways to do this sort of action and, in my opinion, you would be better off learning them since they'll make your code much more readable and easy to maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With