List comprehensions provide a compact way to create lists. In many cases we would like to make new lists where each element is the result of some operations applied to each member of another sequence. Comprehensions are considered to be very "Pythonic" style of coding, as they simplify the code and make it shorter and clearer
# List Comprehensions my_list = [1, 2, 3, 4, 5] new_list = [x + 2 for x in my_list] print(new_list)
When not to use a List Comprehension?
There are two reasons that make conventional for loops a better option:
- The list is redundant
- The logic is too long
List comprehensions create lists. Using comprehensions as a way to avoid conventional for loops is great when the lists are needed. If however this is not the case, it is best to use for loops
When the operations we apply are complicated and the logic is too long, it is best not to use comprehensions.Complicated and long logic, makes the use of list comprehensions counterproductive as it makes the code harder to read and understand.
How to Remove Items From a List While Iterating
Using list comprehension simplifies the way to do it. It is easy to create a new list containing only the elements we don't want to remove. With slicing we can override (mutate) the existing list.
How to reomve from a list all uppercases:
# List Comprehensions my_list = ['A', 'b', 'c', 'D', 'e'] # create a new list: new_list = [x for x in my_list if x.islower()] print(new_list) # mutate current list my_list[:] = [x for x in my_list if x.islower()] print(my_list)