TIL: How to use list comprehensions in python
In the past, if I wanted to make a new list by pulling values out of an existing list based on a condition I would have done something like:
def listItems():
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
new = []
for num in a:
if num % 2 != 0:
new.append(num)
print new
But, I figured out via https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions that list comprehenisions can dramatically compress these functions while still maintaining readability. Here’s an example of a list comprehension that would render the same output as the expanded function above:
def listComp():
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
new = [ num for num in a if num % 2 != 0]
print new
Boom!
The syntax is a little weird because python has so little structure to it “num for num in a…”, but makes more sense if you’re referencing a tuple, where it would be “( 1, 2 ) for num in a…”
Read other posts