Jun-11-2020, 05:14 PM
(Jun-11-2020, 03:55 PM)Drone4four Wrote: Do all list comprehensions automatically somehow know to append list items automatically?
Sorta, yes. They are list comprehensions, so they return a list of the elements. You don't have to create it by manually appending anything. Likewise a dict comprehension will populate a dict, and a set comprehension will append to a set.
r = range(-5, 6) l = [x for x in r if x % 2 == 0] # all the even numbers. l is created here, no appending to other list. print(l)
Output:[-4, -2, 0, 2, 4]
In your attempt you are appending the entire list generated into an empty list. So you just get an extra level of nesting.