Python Forum
Topic: “Filter numbers with a list comprehension” (PyBite #107)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Topic: “Filter numbers with a list comprehension” (PyBite #107)
#1
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:

 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.
Reply


Messages In This Thread
Topic: “Filter numbers with a list comprehension” (PyBite #107) - by Drone4four - Jun-11-2020, 03:55 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 440 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 8 15,448 Jan-05-2024, 08:30 PM
Last Post: sgrey
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 427 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,049 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Using list comprehension with 'yield' in function tester_V 5 1,176 Apr-02-2023, 06:31 PM
Last Post: tester_V
  List of random numbers astral_travel 17 2,534 Dec-02-2022, 10:37 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 1,252 Nov-13-2022, 01:27 AM
Last Post: menator01
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,454 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  list comprehension 3lnyn0 4 1,360 Jul-12-2022, 09:49 AM
Last Post: DeaD_EyE
  Divide a number by numbers in a list. Wallen 7 7,926 Feb-12-2022, 01:51 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020