Modify a list with a list comprehension?

Viewed 36

Say we have a list foo, I would like to modify that list, whether it'd be add or remove elements from it with out creating or using another list or sequence/data structure in general. Would that be possible to do with a list comprehension or no?

1 Answers

You can't edit a list within a list comprehension, but you can access your list within a list comprehension to build a new list :

foo = list(range(10)) # foo == [0, 1, 2, ..., 9]
bar = [element for element in foo if element % 3 == 2  ]
# bar == [2, 5, 8]

You can also use the filter function to do this kind of filtering (assuming you already have foo).

bar = list(filter(lambda x: x % 3 == 2, foo))
# bar == [2, 5, 8]

As for adding elements to a list based on some logic, I see there a reason why we have for loops and list methods.

Related