Jun-11-2020, 03:55 PM
Here is the task I am working on: Write a script which receives a list of numbers and returns only the even numbers that are > 0 and even (divisible by 2). Use list comprehension.
Here was my final valiant attempt:
I was close but slightly off. The problem with my script is that the
My basic, simple pointed question for all of you is this: Do all list comprehensions automatically somehow know to append list items automatically? Are the append/extend class methods implied or assumed?
This is my effort to solve PyBite #107.
Here was my final valiant attempt:
numbers = list(range(-10, 11)) # numbers = [2, 4, 51, 44, 47, 10] # numbers = [0, -1, -3, -5] result = [] result = [result.append(num) for num in numbers if num % 2 == 0 or num <= 0] print(result)For lines 1-3, you can comment/uncomment them to test different list inputs.
I was close but slightly off. The problem with my script is that the
result
appends None
for every list item generated. The reason why this is wrong is because result
when originally defined is empty (None Type) and for every iteration through the comprehensive list, it just keeps adding None. The solution that the online coursewhere presents is similar to mine (very close) but instead of using the append
class method, it’s just result
. Here is the one line solution: result = [n for n in numbers if n > 0 and n % 2 == 0]
. My basic, simple pointed question for all of you is this: Do all list comprehensions automatically somehow know to append list items automatically? Are the append/extend class methods implied or assumed?
This is my effort to solve PyBite #107.